My java implementation, O(1) space required


  • 0
    C
    public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] strs) {
    	int length = strs.length;
    	if (length == 0) return "";
    	if (length == 1) return strs[0];
    	int right = strs[0].length();
    	for (int i = 0; i < length - 1; i++) {
    		int left = 0;
    		int min = Math.min(strs[i].length(), strs[i + 1].length());
    		right = right < min ? right : min; 
    		while(left < right) {
    			if (strs[i].charAt(left) != strs[i + 1].charAt(left))
    				break;
    			left++;
    		}
    		right = left;
    		if (right == 0) return "";
    	}
    	return strs[0].substring(0, right);
    }	
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.