[LeetCode] Buddy Strings

아르당·2026년 3월 3일

LeetCode

목록 보기
182/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두개의 문자열 s와 goal이 주어졌을 때, s에서 두 글자를 바꿔서 결과가 goal과 같다면 true, 그렇지 않다면 false를 반환해라.
문자 교환은 i != j인 두 인덱스와 i와 j(0부터 시작하는 인덱스)를 취하고 s[i]와 s[j]의 문자를 교환하는 것으로 정의된다.

  • 예를 들어, "abcd"에서 인덱스 0과 2를 바꾸면 "cbad"가 된다.

Example

#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과 같아진다.

Constraints

  • 1 <= s.length, goal.length <= 2 * 10^4
  • s와 goal은 소문자로 구성된다.

Solved

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);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글