• 문제 링크
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);
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 867. Transpose Matrix - Java (0) | 2026.10.28 |
|---|---|
| [LeetCode] 860. Lemonade Change - Java (0) | 2026.10.27 |
| [LeetCode] 844. Backspace String Compare - Java (0) | 2026.10.25 |
| [LeetCode] 836. Rectangle Overlap - Java (0) | 2026.10.24 |
| [LeetCode] 832. Flipping an Image - Java (0) | 2026.10.23 |
댓글