Find longest common prefix?

前端 未结 9 1856
忘掉有多难
忘掉有多难 2020-12-10 03:50

In two strings:

\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"

should return

\"Mary Had a \"

相关标签:
9条回答
  • 2020-12-10 04:23

    A very easy solution can be:

      public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(result)) {
                result = result.substring(0, result.length() - 1);
            }
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-10 04:24

    You don't need to use a StringBuilder - just return the substring:

    public String greatestCommonPrefix(String a, String b) {
        int minLength = Math.min(a.length(), b.length());
        for (int i = 0; i < minLength; i++) {
            if (a.charAt(i) != b.charAt(i)) {
                return a.substring(0, i);
            }
        }
        return a.substring(0, minLength);
    }
    
    0 讨论(0)
  • 2020-12-10 04:24

    This solution applied to a multiple string array. When you have 3 or 4 strings, it's better to use StringBuilder. For 2 strings, it's ok to use substring. Code in C#:

        public string LongestCommonPrefix(string[] strs) {
        if(strs.Length == 0) return string.Empty;
    
        Array.Sort(strs);
    
        var first = strs[0];
        var last = strs[strs.Length - 1];
    
        var sb = new StringBuilder();
        for(int i = 0; i< first.Length; i++)
        {
            if(first[i] != last[i])
            {
                break;
            }
            sb.Append(first[i]);
        }
    
        return sb.ToString();
    }
    
    0 讨论(0)
提交回复
热议问题