【1】Longest Common Prefix(最长共同前缀)

2016-06-27  本文已影响86人  ChristmasJason

[题目地址]https://leetcode.com/problems/longest-common-prefix/

题目概要:

思路1:

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        Arrays.sort(strs);
        StringBuilder result = new StringBuilder();
        char[] first = strs[0].toCharArray();
        char[] last = strs[strs.length - 1].toCharArray();
        
        for (int i = 0; i < first.length; i++) {
            if (last.length > i && last[i] == first[i]) {
                result.append(first[i]);
            } else {
                return result.toString();
            }
        }
        
        return result.toString();
    }
}

思路2:

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(result) != 0) {
                result = result.substring(0, result.length() - 1);
            }
        }
        
        return result;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读