Java solution using String library


  • 0
    V
    public class Solution {
      public String longestCommonPrefix(String[] strs) {
        
        if (strs.length == 0) {
            return "";
        } 
        
        if (strs.length == 1) {
            return strs[0];
        }
        
        String prefix = strs[0];
        
        for (int i = 1;  i < strs.length; i++ ) {
            for (int j = prefix.length(); j >= 0; j --) {
                if (strs[i].startsWith(prefix.substring(0,j))) {
                    prefix = prefix.substring(0,j);
                    break;
                }
            }
    
            if (prefix.isEmpty()) {
                break;
            }
        }
        
        return prefix;
        
      }
    }
    

    Note: the two lines in the outer loop is what makes this code faster than 99.45% of Java solutions...


Log in to reply
 

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