Monday, February 5, 2018

[2018-Interview] Longest Common Prefix

Original question: https://leetcode.com/problems/longest-common-prefix/description/

My answer:


class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        if (strs == null || strs.length <= 0) {
            return sb.toString();
        }
        if (strs.length == 1) {
            return strs[0];
        }
        int i = 0;
        while (i < strs[0].length()) {
            if (isSameForAll(strs, i)) {
                sb.append(strs[0].charAt(i));
                i ++;
            } else {
                break; 
            }
        }
        return sb.toString();
        
    }
    private boolean isSameForAll(String[] strs, int i) {
        for (int j = 1; j < strs.length; j ++) {
            if (i < strs[j].length() ) {                
                if (strs[j].charAt(i) != strs[0].charAt(i)) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
}

Another solution is to start from the first one, compare prefix with next string, until end



public class Solution {
    
    // 1. Method 1, start from the first one, compare prefix with next string, until end;
    // 2. Method 2, start from the first char, compare it with all string, and then the second char
    // I am using method 1 here
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        for(int i = 1; i < strs.length; i++) {
            int j = 0;
            while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
                j++;
            }
            if( j == 0) {
                return "";
        }
            prefix = prefix.substring(0, j);
        }
        return prefix;
    }

}

No comments:

Post a Comment