求最长前缀子串---indexOf()

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

思路一:采用java就是所有字符串一个个字符找过去,知道遇到不同的就输出

class Solution {
    public String longestCommonPrefix(String[] strs) {
if(strs.length == 1)
            return strs[0];
        StringBuilder sb = new StringBuilder();
        
        if(strs.length > 1)
        {
            int len = strs[0].length();
            for(int i = 0; i < len; i++)
            {
                char currch = strs[0].charAt(i);
                for(int j = 1; j < strs.length; j++)
                {
                    
                   if(strs[j].length()<=i ||strs[j].charAt(i) != currch)
                        return sb.toString();
                    //当每个位置的值都相等,且来到最后一组了
                    if(strs[j].charAt(i) == currch && j == strs.length - 1)
                    {
                        sb.append(currch);
                    }
                }
            }
        }
        return sb.toString();
 }



思路二:采用indexOf()和subString,从第二个串开始找与第一个串的公共子串,然后跟第三个串也是同样。就是空间复杂度有点高:

class Solution {
    public String longestCommonPrefix(String[] strs) {
       if(strs.length == 0)
            return "";
        String tmp = strs[0];
        for(int i = 1; i < strs.length; i++){
            //先跟第二个串匹配,找到相同的子串,每次没找到公共子串,则
            //原始串则减1,就是最后一个,直到是公共串,然后匹配下一个子串
            while(strs[i].indexOf(tmp) != 0){
                tmp = tmp.substring(0, tmp.length()-1);
            }
        }
        return tmp;

    }
}

你可能感兴趣的:(LeetCode中等难度刷题)