문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
두개의 문자열 s와 goal이 주어졌을 때, s에서 두 글자를 바꿔서 결과가 goal과 같다면 true, 그렇지 않다면 false를 반환해라.
문자 교환은 i != j인 두 인덱스와 i와 j(0부터 시작하는 인덱스)를 취하고 s[i]와 s[j]의 문자를 교환하는 것으로 정의된다.
#1
Input: s = "ab", goal = "ba"
Output: true
Explanation: s[0] = 'a'와 s[1] = 'b'를 바꾸면 "ba"가 되는데 goal과 같아진다.
#2
Input: s = "ab", goal = "ab"
Output: false
Explanation: s[0] = 'a'과 s[1] = 'b'를 바꿀 수 있는데, "ba"는 goal과 같지 않다.
#3
Input: s = "aa", goal = "aa"
Output: true
Explanation: s[0] = 'a'과 s[1] = 'a'를 바꾸면 "aa"가 되고, goal과 같아진다.
class Solution {
public boolean buddyStrings(String s, String goal) {
if(s.length() != goal.length()){
return false;
}
int l = s.length();
if(s.equals(goal)){
Set<Character> temp = new HashSet<>();
for(char c : s.toCharArray()){
temp.add(c);
}
return temp.size() < goal.length();
}
int i = 0;
int j = l - 1;
while(i < j && s.charAt(i) == goal.charAt(i)){
i++;
}
while(j >= 0 && s.charAt(j) == goal.charAt(j)){
j--;
}
if(i < j){
char[] cArr = s.toCharArray();
char temp = cArr[i];
cArr[i] = cArr[j];
cArr[j] = temp;
s = new String(cArr);
}
return s.equals(goal);
}
}