Find longest common prefix?

前端 未结 9 1876
忘掉有多难
忘掉有多难 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;
    }
    

提交回复
热议问题