본문 바로가기
Problem Solving/LeetCode

[LeetCode] 859. Buddy Strings - Java

by graycode 2026. 10. 26.

• 문제 링크

 

Buddy Strings - LeetCode

Can you solve this real interview question? Buddy Strings - Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-ind

leetcode.com

 

• 풀이 코드

public class Solution {

    public boolean buddyStrings(String s, String goal) {
        int n = s.length();
        if (n != goal.length()) return false;

        if (s.equals(goal)) {
            int[] arr = new int[26];
            for (int i = 0; i < n; i++) if (++arr[s.charAt(i) - 'a'] > 1) return true;
            return false;
        }

        int a = -1, b = -1;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == goal.charAt(i)) continue;
            if (a == -1) a = i;
            else if (b == -1) b = i;
            else return false;
        }

        return b != -1 && s.charAt(a) == goal.charAt(b) && s.charAt(b) == goal.charAt(a);
    }

}

댓글