Fast running time Java solution.


  • 0
    R
    public class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if(len == 0)
        return "";
        if(len == 1)
        return strs[0];
        StringBuffer buffer = new StringBuffer();
        int j=0;
        while(true){
             if(strs[0].length()-1 <j)
             return buffer.toString();
             char c = strs[0].charAt(j);
            for(int i =1; i<len; i++){
              if(strs[i].length()-1< j)
                return buffer.toString();
              else if(strs[i].charAt(j) != c)
                return buffer.toString();
            }
             buffer.append(c);
             j++;
            
        }
    }
    

    }


Log in to reply
 

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