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:
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"
문제 요약:
두 문자열이 주어졌을 때, 두 문자열을 서로 유사하게 만들 수 있는지 확인하는 문제입니다.
풀이과정 설명:
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());
}
}
735. Asteroid Collision (0) | 2023.11.16 |
---|---|
2390. Removing Stars From a String (0) | 2023.11.16 |
724. Find Pivot Index (0) | 2023.11.11 |
1732. Find the Highest Altitude (0) | 2023.11.11 |
1493. Longest Subarray of 1's After Deleting One Element (0) | 2023.11.06 |