Leetcode Longest Common Prefix Problem
Solution of Leetcode Longest Common Prefix Problem
Suboor Khan
Software Engineer
TypescriptProblem solving
14.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.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters.
Solution:
function longestCommonPrefix(strs: string[]): string {
let result: string = '';
const targettedString: string = strs[0];
for(let x = 0; x < targettedString.length; x++) {
const currentChar = targettedString[x];
for(let y = 0; y < strs.length; y++) {
if(strs[y][x] !== currentChar) return result;
}
result += currentChar
}
return result;
};