LeetCode 14. Longest Common Prefix

14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

 

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

思路:取给定字符串数组中的第一个字符串为baseline,与余下的字符串们匹配。具体地,建立StringBuilder ans,当检查完并确认所有字符串都含有chs[i]时,将chs[i]推入到ans中。检查中间一旦遇到 当前被检查的字符串太短 或 当前被检查的字符串不含有chs[i]这个字符 时,直接返回结果。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder ans = new StringBuilder();
        char[] chs = strs[0].toCharArray();
        for(int i=0;i<chs.length;i++){
            for(int j=1;j<strs.length;j++){
                if(i>=strs[j].length()||strs[j].charAt(i)!=chs[i]){
                    return ans.toString();
                }
            }
            ans.append(chs[i]);
        }
        return ans.toString();
    }
}

你可能感兴趣的:(数据结构与算法,leetcode,算法)