题目: 最长公共前缀

来自智得网
跳转至: 导航、​ 搜索


最长公共前缀

难度:简单

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

 

示例 1:

输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

 

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成


分析

从位置0取出依此取出字符串数组中每个字符串中对应数字的字符,如果这些字符相等,将该字符append到结果字符串的后面,同时位置向后移动,否则循环结束。

题解

public class Solution {
    public static String solute(String[] strs){
        String result = "";
        int index = 0;
        while(true){
            if(strs[0].length() <= index){
                break;
            }
            char c = strs[0].charAt(index);
            for(int i = 1; i < strs.length; i ++){
                if(strs[i].length() <= index){
                    break;
                }
                if(strs[i].charAt(index) != c){
                    break;
                }
            }

            result += c;
            index ++;
        }
    }
}