[leetcode] Longest Common Prefix

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

https://oj.leetcode.com/problems/longest-common-prefix/

思路1:以第一个字符串为基准,依次比较后面字符串每一位的情况,如有不相同或者有字符串提前结束即返回。

 

public class Solution {
	public String longestCommonPrefix(String[] strs) {
		int n = strs.length;
		if(n<1)
			return "";
		int len0 = strs[0].length();
		int i, j;
		outer: for (i = 0; i < len0; i++) {
			char cur = strs[0].charAt(i);
			for (j = 1; j < n; j++) {
				if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
					break outer;
				}

			}
		}
		return strs[0].substring(0, i);

	}

	public static void main(String[] args) {
		System.out.println(new Solution().longestCommonPrefix(new String[] {
				"abbasda", "abb", "abbc" }));
		System.out.println(new Solution().longestCommonPrefix(new String[] {
				"", "ab", "ac" }));
		System.out.println(new Solution()
				.longestCommonPrefix(new String[] { "abc" }));
		System.out.println(new Solution()
		.longestCommonPrefix(new String[] {}));

	}
}

 

 

第二遍记录:

  思路不变,注意String的length() 和 数组的 length

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null)
            return null;
        if(strs.length==0)
            return "";
        int len = strs[0].length();
        for(int i=0;i<len;i++){
            char ch = strs[0].charAt(i);
            for(int j=1;j<strs.length;j++){
                if(i>=strs[j].length()||ch!=strs[j].charAt(i))
                    return strs[0].substring(0,i);
            }
        }
        return strs[0];
    }
}

 

 

 

 

posted @ 2014-06-26 19:19  jdflyfly  阅读(157)  评论(0编辑  收藏  举报