
문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
같은 길이의 2개의 문자열 s1과 s2가 주어진다. string swap은 문자열 내에서 2개의 인덱스를 선택하고(반드시 서로 다를 필요 없음) 인덱스에 문자를 바꾸는 작업이다.
문자열에서 정확히 하나의 문자를 최대 한 번 string swap을 해서 두 문자열을 같게 만들 수 있다면 true를 반환해라. 그렇지 않다면 false를 반환해라.
#1
Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: 예를 들어, s2의 첫 번째와 마지막 문자를 바꾸면 "bank"가 된다.
#2
Input: s1 = "attack", s1 = "defend"
Output: false
Explanation: 한 번의 string swap으로 같게 할 수 없다.
#3
Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: 두 문자열은 이미 같고, string swap 작업을 할 필요가 없다.
class Solution {
public boolean areAlmostEqual(String s1, String s2) {
if(s1.equals(s2)){
return true;
}
int first = -1;
int second = -1;
int count = 0;
for(int i = 0; i < s1.length(); i++){
if(s1.charAt(i) != s2.charAt(i)){
count++;
if(count == 1){
first = i;
}else if(count == 2){
second = i;
}else{
return false;
}
}
}
return count == 2 && s1.charAt(first) == s2.charAt(second) && s1.charAt(second) == s2.charAt(first);
}
}