1ms Java solution, beats 86.81%


  • 0
    M
    public String longestCommonPrefix(String[] strs) {
    	if (strs == null || strs.length == 0)
    		return "";
    	if (strs.length == 1)
    		return strs[0];
        //find prefix of 1st and 2st string
    	String prefix = longestPrefix(strs[0], strs[1]);
       //check if rest of elements have the same prefix
    	for (int i = 2; i < strs.length; i++) {
           //if  prefix doesn't match, remove the last element until matches
    		while (!strs[i].startsWith(prefix)) {               
    			prefix = prefix.substring(0, prefix.length() - 1);
    		}
    	}
    	return prefix;
    }
    
    //find common longest prefix of 2 strings
    public String longestPrefix(String s, String p) {
    	String prefix = "";
    	int i = 1;
    	while (i <=s.length() && i <= p.length() && p.startsWith(s.substring(0, i)) ) {
    		prefix = s.substring(0, i);
    		i++;
    	}
    	return prefix;
    }

  • 0
    I
    	if(strs.length == 0) return "";
    	if(strs.length == 1) return strs[0];
    	
    	String longest = new String();
    	
    	int firstLen = strs[0].length();
    	int k = 0;
               //See if the substring(starting with one char at a time) of first String is the
               prefix of all the other Strings 
    	while(k < firstLen)
        {
    	   int count = 1;
      	   String prefix = strs[0].substring(0, k+1);
    	   for(int i = 1; i < strs.length; i++)
           {
      	       if(strs[i].startsWith(prefix))
      	       {
      		     count++;
      	       }
      	      if(count == strs.length)
      	      {
      		     longest = prefix;
      	      }
           }
    	   k++;
        }
    	return longest;

Log in to reply
 

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