๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Longest Common Prefix

by dkswnkk 2021. 11. 11.

๋ฌธ์ œ

 

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;
    }
};

 

ํ’€์ด

์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ฌธ์ž๋ฅผ ๋ถ„ํ• ํ•ด ๊ฐ€๋ฉด์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ๋ฌธ์ž๋“ค์„ ์ฒดํฌํ•˜๋Š”๋ฐ, ๋ถ„ํ• ํ•œ ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅธ ๋ชจ๋“  ๋ฌธ์ž๋“ค์˜ ๋ถ„ํ• ๊ณผ ๊ฐ™๋‹ค๋ฉด ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Length of Last Word  (0) 2021.11.14
[Leetcode,c++] Container With Most Water  (0) 2021.11.14
[Leetcode,c++] Remove Duplicates from Sorted Array  (0) 2021.11.14
[Leetcode,c++] Permutations  (0) 2021.11.10
[Leetcode,c++] Best Time to Buy and Sell Stock  (0) 2021.11.10
[Leetcode,c++] Climbing Stairs  (0) 2021.11.09

๋Œ“๊ธ€