728x90
Description
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.
Solution
class Solution{
public String longestCommonFix(String[] strs){
if(strs == null || strs.length == 0) return "";
String prefix = strs[0];
for(String s : strs)
while(s.indexOf(prefix) != 0)
prefix = prefix.substring(0,prefix.length()-1);
return prefix;
}
}
prefix = prefix.substring(0,prefix.length()-1) indicates that string is substracted till it reachs till s.indexOf(prefix) == 0
Time complexity O(n) as it iterates through the array
Space Complexity O(1)
'Programming > LeetCode' 카테고리의 다른 글
[LeetCode] #20. Valid Parentheses (0) | 2024.02.08 |
---|---|
[LeetCode] #232. Implement Queue using Stacks (0) | 2024.02.05 |
[LeetCode] #58. Length of Last Word (repeat : 0) (2) | 2024.01.23 |
[LeetCode]#13. Roman to Integer (repeat : 0 ) (0) | 2024.01.22 |
[LeetCode] #169. Majority Element (repeat : 0 ) (0) | 2024.01.21 |