Algorithm ๐ง๐ป๐ป/Leetcode
[Leetcode,c++] Longest Common Prefix
dkswnkk
2021. 11. 11. 00:37
๋ฌธ์
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
์ฝ๋
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans="";
for(int i=0; i<strs[0].length()+1; i++){
string check = strs[0].substr(0,i);
bool flag=true;
for(int k=1; k<strs.size(); k++){
if(strs[k].substr(0,i)!=check){
flag = false;
break;
}
}
if(flag) ans=check;
}
if(strs.size()==1) return strs.front();
return ans;
}
};
ํ์ด
์ฒซ ๋ฒ์งธ ๋ฌธ์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌธ์๋ฅผ ๋ถํ ํด ๊ฐ๋ฉด์ ๋ค๋ฅธ ๋ชจ๋ ๋ฌธ์๋ค์ ์ฒดํฌํ๋๋ฐ, ๋ถํ ํ ๋ฌธ์๊ฐ ๋ค๋ฅธ ๋ชจ๋ ๋ฌธ์๋ค์ ๋ถํ ๊ณผ ๊ฐ๋ค๋ฉด ์ถ๋ ฅํฉ๋๋ค.