[LeetCode] 14. Longest Common Prefix ☆

 

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

 

解法: 

  广度优先搜索:先比较所有字符串的第一个字符,然后比较第二个。。。。如果某一行没有了(说明其为最短的单词)或者遇到不匹配字符,则返回当前匹配到的最长前缀。

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

 

  深度优先搜索:依次将找出的最长前缀res(初始为第一个字符串)与后面的字符串匹配,如果共同前缀变短,更新res。

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

 

posted @ 2017-02-16 16:15  Strugglion  阅读(141)  评论(0编辑  收藏  举报