Longest Common Prefix Java Solution - The Coding Shala
Home >> Interview Questions >> Longest Common Prefix
Longest Common Prefix
Problem:
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: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Longest Common Prefix Java Solution
Approach:
We will check character at every index of every string given in array if not matched then will break the loop.
Java Code::
class Solution { public String longestCommonPrefix(String[] strs) { int len = strs.length; if(strs == null || len == 0) return ""; String check = strs[0]; int index = check.length(); for(int i=1; i< len; i++){ for(int j=0; j< index; j++){ if(j >= strs[i].length() || check.charAt(j) != strs[i].charAt(j)){ index = j; break; } } } return check.substring(0, index); } }
Other Posts You May Like
Comments
Post a Comment