2014年4月8日 星期二

[LeetCode] Longest Common Prefix

Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Solution O(n * c)  c is length of longest common prefix string;


public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs ==null || strs.length == 0)
            return "";
        
        int len = strs[0].length();
        for(int i=0; i< len;i++){
            for(int t=1; t < strs.length;t++){
                if(strs[t].length() <= i || strs[t].charAt(i)!=strs[0].charAt(i) ){
                   return strs[0].substring(0,i);
                }
            }
        }
        return strs[0]; 
    }
}
Key concept: from the position viewpoint, each str need to the same,
otherwise stop procedure. 

沒有留言:

張貼留言