Notice
250x250
Recent Posts
Recent Comments
Link
넘치게 채우기
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal 본문
PS/LeetCode
[LeetCode] 1790. Check if One String Swap Can Make Strings Equal
riveroverflow 2025. 2. 5. 17:51728x90
반응형
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/description/
leetcode - Check if One String Swap Can Make Strings Equal
문제 유형: 투 포인터
문제 난이도: Easy
문제
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
같은 길이의 문자열 s1과 s2가 주어진다.
문자열의 두 인덱스를 최대 한 번만 스왑해서 문자열이 같다면, true를, 아니면 false를 반환하시오.
풀이
처음부터 같으면 스왑할 필요 없이 true를 반환하면 된다.
왼쪽 끝 인덱스부터 오른쪽으로 같은 글자인동안 스위핑한다.
반대도 똑같이 해준다.
왼쪽 시작과 오른쪽 시작에서 멈춘 지점에서 스왑해보고 비교한 값을 반환한다.
코드
C++
#pragma GCC optimize("O3", "unroll-loops");
static const int __ = [](){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}();
class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
if(s1 == s2) return true;
int left = 0, right = s1.size()-1;
while(s1[left] == s2[left]) left++;
while(s1[right] == s2[right]) right--;
swap(s2[left], s2[right]);
return s1 == s2;
}
};
Go
func areAlmostEqual(s1 string, s2 string) bool {
if s1 == s2 {
return true
}
left := 0
right := len(s1) - 1
for left < len(s1) && s1[left] == s2[left] {
left++
}
for right >= 0 && s1[right] == s2[right] {
right--
}
if left >= right {
return false
}
s2Bytes := []byte(s2)
s2Bytes[right], s2Bytes[left] = s2Bytes[left], s2Bytes[right]
s2 = string(s2Bytes)
return s1 == s2
}
728x90
반응형
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 1726. Tuple with Same Product (0) | 2025.02.06 |
---|---|
[LeetCode] 1800. Maximum Ascending Subarray Sum (0) | 2025.02.04 |
[LeetCode] 3105. Longest Strictly Increasing or Strictly Decreasing Subarray (0) | 2025.02.03 |
[LeetCode] 1752. Check if Array Is Sorted and Rotated (0) | 2025.02.02 |
[LeetCode] 3151. Special Array I (0) | 2025.02.01 |