728x90
https://leetcode.com/problems/longest-common-prefix/submissions/
Longest Common Prefix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string longestCommonPrefix(vector<string> strs){
string answer = "";
for(int i=0; i<strs[0].size(); i++){
for(int j=1; j<strs.size(); j++){
if(strs[0][i] != strs[j][i]) return answer;
}
answer += strs[0][i];
}
return answer;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cout << longestCommonPrefix({"flower", "flow", "flight"}) << '\n';
cout << longestCommonPrefix({"dog","racecar","car"}) << '\n';
}
맨 첫 번째 원소를 사용해서 다른 원소들을 체크하면서 만약 하나라도 일치하지 않는다면 바로 common prefix를 할당하고 있는 answer를 출력해준다.
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy] strStr() (0) | 2022.08.12 |
---|---|
[LeetCode/easy] Valid Parentheses (0) | 2022.08.12 |
[LeetCode/easy] Roman To Integer (0) | 2022.04.18 |
[LeetCode/easy] PalindromeNumber (0) | 2022.04.18 |
[LeetCode/easy] TwoSum (0) | 2022.04.18 |