文章--LeetCode算法--LongestCommonPrefix

LongestCommonPrefix

问题描述

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

实例

在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 "A"

在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

实现代码

  public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs.length == 0)
                return "";
            if (strs.length == 1)
                return strs[0];
            StringBuilder sb = new StringBuilder();
            int n = Integer.MAX_VALUE;
            boolean finished = false;
            for (int i = 0; i < strs.length; ++i)
                n = Math.min(strs[i].length(), n);
            for (int i = 0; i < n; ++i) {
                char c = strs[0].charAt(i);
                for (int j = 1; j < strs.length; ++j) {
                    if (strs[j].charAt(i) != c) {
                        finished = true;
                        break;
                    }
                }
                if (finished)
                    break;
                sb.append(c);
            }
            return sb.toString();
        }
posted @ 2019-07-19 10:11  AI,me  阅读(70)  评论(0)    收藏  举报