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 lower-case English letters.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string str = "";
if (strs.size() == 1)
{
str = strs[0];
}
else
{
for (int i = 1 ; i <= strs[0].length(); i++)
{
string temp = strs[0].substr(0, i);
for (int j = 1; j < strs.size(); j++)
{
if (strs[j].find(temp) == 0)
{
if (j == strs.size() - 1)
{
str = temp;
}
}
else
{
break;
}
}
}
}
return str;
}
};
'Challenge' 카테고리의 다른 글
[Programmers] Hash - 베스트앨범 (0) | 2021.09.29 |
---|---|
[LeetCode] Container With Most Water (0) | 2021.09.29 |
[LeetCode] Integer to Roman (0) | 2021.09.29 |
[LeetCode] Roman to Integer (0) | 2021.09.29 |
[Codility] CountDiv (0) | 2021.09.27 |