상세 컨텐츠

본문 제목

1657. Determine if Two Strings Are Close

LeetCode

by 10002s 2023. 11. 13. 00:35

본문

Determine if Two Strings Are Close - LeetCode

두 문자열이 서로 유사하다고 간주될 때, 한 문자열을 다른 문자열로 바꿀 수 있는지 여부를 결정하는 문제입니다.
다음 두 연산을 사용하여 두 문자열이 유사한지 확인합니다:
연산 1: 기존 문자열에서 두 문자를 서로 바꿉니다.
예시: abcde -> aecdb
연산 2: 기존 문자를 다른 문자로 변환합니다. 두 문자가 서로 대체됩니다.
예시: aacabb -> bbcbaa (모든 'a'를 'b'로, 모든 'b'를 'a'로 변환)
두 문자열 word1과 word2가 주어졌을 때, word1을 word2로 바꿀 수 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

 

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

 

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

 

문제 요약:

두 문자열이 주어졌을 때, 두 문자열을 서로 유사하게 만들 수 있는지 확인하는 문제입니다.

풀이과정 설명:
  1. 두 문자열의 길이가 다르면 false를 반환합니다. 길이가 같아야 두 문자열이 서로 대응될 수 있습니다.
  2. 각 문자열의 문자 빈도를 계산합니다.
  3. 두 문자열의 문자 빈도가 같아야 연산을 통해 서로 변환할 수 있습니다.
  4. 각 문자열의 문자 빈도를 정렬하여 서로 대응되는 문자가 동일한지 확인합니다.
class Solution {
    public boolean closeStrings(String word1, String word2) {
        if (word1.length() != word2.length()) return false;
        
        int[] cnt1 = new int[26];
        int[] cnt2 = new int[26];

        for(char chr : word1.toCharArray()){
            cnt1[chr - 'a']++;
        }
        for(char chr : word2.toCharArray()){
            cnt2[chr - 'a']++;
        }
        /*
        for(int i = 0; i < cnt1.length ; i++){
            if((cnt1[i] > 0 && cnt2[i] == 0) || (cnt2[i] > 0 && cnt1[i] == 0)) return false;
        }
        */
        Arrays.sort(cnt1);
        Arrays.sort(cnt2);

        //return Arrays.equals(cnt1,cnt2);
        
        return Arrays.equals(cnt1, cnt2)
            && Arrays.equals(word1.chars().distinct().sorted().toArray(), word2.chars().distinct().sorted().toArray());

    }
}

 

반응형

'LeetCode' 카테고리의 다른 글

관련글 더보기