코린이의 소소한 공부노트

[LeetCode/Easy] 2744. Find Maximum Number of String Pairs 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 2744. Find Maximum Number of String Pairs

무지맘 2023. 6. 30. 23:52

1. Input

1) String[] words

 

2. Output

1) words에서 찾을 수 있는 순서쌍의 최대 수를 반환

- words[i]words[j]가 순서쌍이 되려면 i<j이고 words[i]를 뒤집으면 words[j]가 되어야 한다.

 

3. Constraint

1) 1 <= words.length <= 50

2) words[i].length == 2

3) words에 중복 단어는 없다.

4) words의 단어들은 영어 소문자로 이루어져 있다.

 

4. Example

Input: words = ["cd","ac","dc","ca","zz"] -> Output: 2

Input: words = ["ab","ba","cc"] -> Output: 1

Input: words = ["aa","ab"] -> Output: 0

 

5. Code

class Solution {
    public int maximumNumberOfStringPairs(String[] words) {
        boolean[] visited = new boolean[words.length];
        int count = 0;
        for(int i=0 ; i<words.length-1 ; i++){
            if(visited[i]) continue;
            for(int j=i+1 ; j<words.length ; j++)
                if(words[i].charAt(0)==words[j].charAt(1) && words[i].charAt(1)==words[j].charAt(0)){
                    visited[j] = true;
                    count++; break;
                }
        }
        return count;
    }
}

- 100%, 96%
- 중복 단어가 없는 것을 활용하기 위해 체크한 단어는 건너뛸 수 있도록 visited를 이용했는데, 효과가 매우 컸다!