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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容