[Leetcode] 686. Repeated String Match (re) C++

Algorithm|2021. 11. 22. 15:48
반응형
 

Repeated String Match - 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

O(n²)로 a가 커질 때마다 확인하는 식으로 짰는데, 너무 길어져 버리면 Time Limit이 되어버림

 

class Solution {
public:
    int repeatedStringMatch(string a, string b) 
    {
        int count = 1;
        string a_plus = a;
        
        if(b.size() > 100)
            return -1;
        
        for(int i=0; i<b.size(); i++)
        {
                
            
            if(a_plus.size() >= b.size())
                for(int k = 0; k<= a_plus.size() - b.size(); k++)
                {
                    string sub = a_plus.substr(k,b.size());    
                    
                    if(sub.compare(b) == 0)
                        return count;
                }

                
            
            a_plus += a;
            count++;
            

        }
        
        return -1;
    }
};
반응형

'Algorithm' 카테고리의 다른 글

[백준] 10757. 큰수 A+B  (1) 2021.11.23
[백준] 15947. 아기 석환 뚜루루 뚜루  (1) 2021.11.23
[백준] 5598. 카이사르 암호  (0) 2021.11.21
[백준] 17210. 문문문  (0) 2021.11.21
[백준] 17211. 좋은날 싫은날  (0) 2021.11.21

댓글()