Java o(n*n) easy solution


  • 0
    R
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs==null){
                return null;
            }
            if(strs.length==0){
                return "";
            }
            String perfix = strs[0];
            int length = perfix.length();
            for(String str:strs){
                int index=0;
                // when the letter is not same, then get current length
                for(int index2=0;index2<length&&index2<str.length();index2++){
                    if(str.charAt(index2) == perfix.charAt(index)){
                        index++;
                    }
                    else{
                        break;
                    }
                }
                length=index;
            }
            return perfix.substring(0,length);
        }
    }

Log in to reply
 

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