LeetCode14(最长公共前缀)

2019-11-04  本文已影响0人  gerryjia

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

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

示例 1:
输入: ["flower","flow","flight"]
输出: "fl"

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

所有输入只包含小写字母 a-z 。
解题思路

从前往后枚举字符串的每一列,先比较每个字符串相同列上的字符(即不同字符串相同下标的字符)然后再进行对下一列的比较。

代码实现
class SecondSolution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";

        for (int i = 0; i < strs[0].length(); i++) {
            char s = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (i == strs[j].length() || strs[j].charAt(i) != s) {
                    return strs[0].substring(0, i);
                }

            }
        }
        return strs[0];
    }
}

public class ByteDanceSecond {
    public static void main(String[] args) {
        System.out.println("请输入数组大小:");
        Scanner scanner1 = new Scanner(System.in);
        int num;
        num = scanner1.nextInt();

        System.out.println("请输入序列:");
        Scanner scanner2 = new Scanner(System.in);
        String[] s = new String[num];
        for (int i = 0; i < num; i++) {
            s[i] = scanner2.next();
        }
        String ret = new SecondSolution().longestCommonPrefix(s);

        String out = (ret);

        System.out.print(out);

    }
}

上一篇 下一篇

猜你喜欢

热点阅读