Longest Common Prefix–LeetCode#14

1.Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
(求一个字符串数组中最长的公共前缀)

Example:

{“ss”,”ssh”,”sshc”,”sc”}
return “s”;

思路:循环每个字符串,使用charAt()方法找出代码单元,如果相同通过StringBuilder连接返回。

public class LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs==null || strs.length==0){
            return "";
        }
        String temp = strs[0];
        for (int i=0;i<strs.length;i++){
            StringBuilder sb = new StringBuilder();
            int length = 0;
            if (temp.length() >= strs[i].length()){
                length = strs[i].length();
            }else {
                length = temp.length();
            }
            for(int j=0;j<length;j++){
                if(temp.charAt(j) == strs[i].charAt(j)){
                    sb.append(temp.charAt(j));
                }else{
                    break;
                }
            }
            temp = sb.toString();
        }
        return temp;
    }
    public static void main(String[] args) {
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String[] s = {"ssh","ss","ssb","sshc"};
        System.out.println(longestCommonPrefix.longestCommonPrefix(s));
    }
}

 

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部