LeetCode题解-14-Longest Common Prefix

解题思路

题目是要寻找所有字符串中最长的公共开头部分。我的做法是对于某个位置的字符,看看其他字符串同样的位置是否也是这个字符,如果是则继续往后找,如果不是则表示最长的公共开头部分。为了避免越界,首先找到字符串的最小长度,用这个位置做边界,后面就不需要判断了。

参考源码

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLen = Integer.MAX_VALUE;
        for (String str : strs) {
            int len = str.length();
            if (len < minLen) {
                minLen = len;
            }
        }

        for (int i = 0; i < minLen; i++) {
            if (!isPositionMatch(strs, i)) {
                return strs[0].substring(0, i);
            }
        }
        return strs[0].substring(0, minLen);
    }

    private boolean isPositionMatch(String[] strs, int i) {
        char c = strs[0].charAt(i);
        for (int j = 1, len = strs.length; j < len; j++) {
            if (strs[j].charAt(i) != c) {
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/mccxj/article/details/62237117
今日推荐