Thursday, July 9, 2015

Longest Common Prefix

Given k strings, find the longest common prefix (LCP).
Have you met this question in a real interview? 
Yes

Example
For strings "ABCD""ABEF" and "ACEF", the LCP is"A"
For strings "ABCDEFG""ABCEFG" and "ABCEFA", the LCP is "ABC"

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    public String longestCommonPrefix(String[] strs) {
        // write your code here
        if(strs == null || strs.length == 0) return "";
        if(strs.length == 1) return strs[0];
        String res = "";
        for(int i = 0; i < strs[0].length(); i++){
            char c = strs[0].charAt(i);
            boolean isPass = true;
            for(int j = 1; j < strs.length; j++){
                
                if(strs[j].length() < i+1 || strs[j].charAt(i) != c){
                    isPass = false;
                    break;
                }
            }
            if(isPass){
                res += c;
            } else return res;
        } 
        
        return res;
    }
}

No comments:

Post a Comment