Home » leet code » Leet Code : longest common prefix string C++ ,java , Python Solution

Leet Code : longest common prefix string C++ ,java , Python Solution

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Java Solution

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==1)
            return strs[0];
        Arrays.sort(strs);
        int len=strs[0].length();
        
        StringBuilder builder =new StringBuilder();
        
        int c=0;
        while(c<len){
            if(strs[0].charAt(c)==strs[strs.length-1].charAt(c)){
                builder.append(strs[0].charAt(c));
            }
            else{
                break;
            }
            c++;
        }
        return builder.toString();
    }
}

C++ solution

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string str = strs[0];
        string finl="";
        
        for(int i = 0; i < str.size(); i++)
        {
             char currentChar = str[i];
            for(int j = 1; j < strs.size(); j++)
            {
                if(strs[j][i] != currentChar){
                    return finl;
                }
                
            }
            finl += currentChar;
        }
        return finl;
    }
};

Python Solution :

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        ans = ''
        n = len(min(strs))
        for i in range(n):
            if all(x[i]==strs[0][i] for x in strs):
                ans = ans + strs[0][i]
            else:
                break
        return ans

JavaScript solution

Leave a Reply