Longest Common Prefix

Given k strings, find the longest common prefix (LCP).

Example

  • For strings "ABCD", "ABEF" and "ACEF", the LCP is "A"
  • For strings "ABCDEFG", "ABCEFG" and "ABCEFA", the LCP is "ABC"

思路

  1. 首先取String[] 中的第一个String 作为第一个被比较的对象
  2. 增加一个函数处理String[] 中元素, 依次两两比较找到commonPrefix,再用这个commonPrefix与后面的string比较找commonPrefix,依此类推
public class Solution {
    /*
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    public String longestCommonPrefix(String[] strs) {
        // write your code here
        // 首先取String[] 中的第一个String 作为第一个被比较的对象
        // 增加一个函数处理String[] 中元素, 依次两两比较找到commonPrefix,再用这个prefix与后面的string比较找commonPrefix,依此类推
        
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            result = findCommonPre(result, strs[i]);
        }
        return result;
    }
    
    public String findCommonPre(String s1, String s2) {
        StringBuilder result = new StringBuilder();
        
        int i = 0;
        while (i < s1.length() && i < s2.length()) {
            if (s1.charAt(i) != s2.charAt(i)) {
                break;
            }
            result.append(s1.charAt(i));
            i++;
        }
        return result.toString();
    }
}

你可能感兴趣的:(Longest Common Prefix)