码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Longest Common Prefix

时间:2015-12-15 14:04:40      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

思路:

以第一个字符串为基准,然后循环比较

package string;

public class LongestCommonPrefix {

    public String longestCommonPrefix(String[] strs) {
        int len = 0;
        if (strs == null || (len = strs.length) == 0) return "";

        StringBuilder sb = new StringBuilder();
        int i = 0;
        int len0 = strs[0].length();
        while (i < len0) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < len; ++j) {
                if (i >= strs[j].length() || strs[j].charAt(i) != c)
                    return sb.toString();
            }
            
            sb.append(c);
            ++i;
        }
        
        return sb.toString();
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] strs = { "abc", "ab", "abcd", "abcdef" };
        LongestCommonPrefix l = new LongestCommonPrefix();
        System.out.println(l.longestCommonPrefix(strs));
    }

}

 

LeetCode - Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5047887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!