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

Longest Common Prefix

时间:2015-03-15 18:11:46      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:

Longest Common Prefix

问题:

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

思路:

  简单的string运算

我的代码:

技术分享
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0) return "";
        String comm = strs[0];
        for(int i = 1; i < strs.length; i++)
        {
            comm = getCommon(comm,strs[i]);
        }
        return comm;
    }
    public String getCommon(String left, String right)
    {
        int i = 0;
        while(i < left.length() && i < right.length())
        {
            if(left.charAt(i) == right.charAt(i)) i++;
            else    break;
        }
        return left.substring(0,i);
    }
}
View Code

 

Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4340038.html

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