넘치게 채우기

[LeetCode] 1662. Check If Two String Arrays are Equivalent 본문

PS/LeetCode

[LeetCode] 1662. Check If Two String Arrays are Equivalent

riveroverflow 2023. 12. 1. 21:35
728x90
반응형

https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/description/

 

Check If Two String Arrays are Equivalent - LeetCode

Can you solve this real interview question? Check If Two String Arrays are Equivalent - Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array

leetcode.com

leetcode - Check If Two String Arrays are Equivalent

문제 유형 : 문자열 처리

문제 난이도 : Easy

 

문제

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenated in order forms the string.

 

두 문자열 배열 word1과 word2가 주어진다. 두 문자열 배열이 같은 문자열을 나타내면 true를, 아니면 false를 반환하라.

문자열들을 순서대로 다 붙였을 때를 비교하라.

 

풀이

문제 그대로 문자열들을 모두 붙여서 비교해주면 된다.

 

다른 풀이가 또 하나 있다.

문자열 배열의 각 요소들의 각 글자들을 하나씩 서로 체킹하면서 배열을 끝까지 순회하는 것이다.

끝까지 순회하면 true, 중간에 다른 부분이 있으면 false를 반환하면 된다.

 

 

코드

C++

문자열들을 붙이는 풀이는 식상해서, 글자 접근으로 해보았다.

공간 복잡도를 O(1)로 아낄 수 있다.

class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);

        int w1 = 0;
        int w2 = 0;
        int i1 = 0;
        int i2 = 0;
        while(true) {
            const char c1 = word1[w1][i1];
            const char c2 = word2[w2][i2];

            if(c1 != c2) return false;

            i1++;
            i2++;

            if(i1 >= word1[w1].size()) {
                w1++;
                i1 = 0;
            }
            if(i2 >= word2[w2].size()) {
                w2++;
                i2 = 0;
            }

            if(w1 >= word1.size() && w2 >= word2.size()) break;
            if(w1 >= word1.size() || w2 >= word2.size()) return false;
        }

        return true;
    }
};
 
728x90
반응형