leetCode:最长公共前缀

leetCode:最长公共前缀

题目:

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”

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

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

思路:

暴力解决:外层循环下标为0的字符串,内层循环判断每个字符串。

代码:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int count = 0;
        for (int i = 0; i < strs[0].length(); i++) {
            char ch = strs[0].charAt(count);
            boolean flush = true;
            for (int j = 1; j < strs.length; j++) {
                try {
                    if (strs[j].charAt(count) != ch) {
                        flush = false;
                        break;
                    }
                } catch (StringIndexOutOfBoundsException e) {
                    flush = false;
                    break;
                }
            }
            if (flush) {
                count++;
            }
        }
        return strs[0].substring(0, count);
    }
}
上一篇:基于 Python 的计算思维训练——函数


下一篇:【单目标优化求解】基于matlab混合正弦余弦算法和Lévy飞行改进麻雀算法求解单目标优化问题【含Matlab源码 1653期】