Java: different approach

  • 0

    public class Solution {
    public String longestCommonPrefix(String[] strs) {
    here we first check first character of all strings in the array
    then second chracter of all stings in the array and so on. once
    we find that a character is not the same or any string has no
    more characters we break the loops and hence the loops are
    terminated much earlier than other approaches.
    in implementation we compare characters of the first string with
    rest of the strings

        if(strs==null) return null;
        if(strs.length==0) return "";
        if(strs.length==1) return strs[0];
        if(strs[0].length()==0) return "";
        char test='0';
        boolean flag=false;
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<strs[0].length();i++){ // iterates through the chars of string at index 0
            test = strs[0].charAt(i);
            for(int j=1;j<strs.length;j++){
                // compares the character of first string with character present 
                // at that position for rest of the strings
                if(i>=strs[j].length() || strs[j].charAt(i) != test){
            if(flag) break;
            sb.append(""+test);// we append a character if we find all were the same
        return ""+sb;


Log in to reply

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