Longest Common Prefix

 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.



class Solution {
    public String longestCommonPrefix(String[] strs) {

     StringBuilder sb= new StringBuilder();

    Arrays.sort(strs); // sort array

char [] first= strs[0].toCharArray(); // first element

char [] last= strs[strs.length-1].toCharArray(); // last element  bcz all sorted that why we compare first and last

for(int i=0;i<first.length;i++)
{
    if(first[i]!=last[i])
    {
        break;
    }
    sb.append(first[i]);
}

return sb.toString();

    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence