본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 1072. Flip Columns For Maximum Number of Equal Rows

반응형

https://leetcode.com/problems/greatest-common-divisor-of-strings/description/

 

Greatest Common Divisor of Strings - LeetCode

Greatest Common Divisor of Strings - For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both

leetcode.com

전수조사 문제였습니다.

📕 풀이방법

📔 풀이과정

str2의 부분 문자열을 구해 str1, str2로 나눠지는지 여부를 판별하고 나누어 진다면 더 큰 size를 저장해줍니다.


📕 Code

📔 C++

class Solution {
public:
    bool isDivisorString(string str, string piv){
        for(int i = 0; i < str.size(); i += piv.size()) {
            string sub = str.substr(i, piv.size());
            if(sub != piv) return false;
        }
        return true;
    }

    string gcdOfStrings(string str1, string str2) {
        string ans = "";
        for(int i = 0; i < str2.size(); i++) {
            string subStr2 = str2.substr(i);
            int isDivisor = 1;
            isDivisor = min(isDivisorString(str1, subStr2), isDivisorString(str2, subStr2));
            if(isDivisor && ans.size() < subStr2.size())
                ans = subStr2;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.