Sunday, February 24, 2013

[LeetCode] Longest Common Prefix


Thought:
For every string in the array, test their first character, and then second and then... until we found mismatch.

Code:
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) return "";
        
        int len = 0;
        boolean flag = true;
        while(flag){
            for(int i = 0; i < strs.length; i++){
                if( len >= strs[i].length() ){
                    flag = false;
                    break;
                }else if( strs[i].charAt(len) != strs[0].charAt(len) ){
                    flag = false;
                    break;
                }
            }
            if(flag) len++;
        }
        return strs[0].substring(0,len);        
    }
}

No comments:

Post a Comment