java 4ms solution


  • 0
    G
    public String longestCommonPrefix(String[] strs) {
            if (strs == null)  return null;        
            if (strs.length == 0 || (strs.length > 0 && strs[0].equals(""))) {return "";}
            if (strs.length == 1) {return strs[0];}                
            boolean hasMore = true;
            int i = 0, j;
            char prevChar = strs[0].charAt(0), c = prevChar;
            StringBuilder sb = new StringBuilder();
            while (hasMore) {
            	if (i >= strs[0].length()) {
            		hasMore = false;
            	} else {
            		prevChar = strs[0].charAt(i);
            	}
            	for (j = 1; j < strs.length && hasMore; j++) {
                	if (i >= strs[j].length()) {
                		hasMore = false;
                	} else {
                		c = strs[j].charAt(i);
                		if (c != prevChar) {
                			return sb.toString();
                		}             		
                	}	
            	}
            	if (hasMore) sb.append(c);
            	i++;
            }
            return sb.toString();
        }

Log in to reply
 

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