2023-07-03 Daily Challenge
Today I have done leetcode's July LeetCoding Challenge with cpp.
July LeetCoding Challenge 3
Description
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-indexed) such that i != j and swapping the characters at s[i] and s[j].
- For example, swapping at indices
0and2in"abcd"results in"cbad".
Example 1:
Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 104sandgoalconsist of lowercase letters.
Solution
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.size() != B.size())return false;
vector<int> cnt(128);
int pos = -1;
for(int i = 0; i < A.size(); ++i) {
cnt[A[i]] ++;
if(A[i] != B[i] && pos == -1) {
pos = i;
} else if (A[i] != B[i]) {
char temp = A[i];
A[i] = A[pos];
A[pos] = temp;
return A == B;
}
}
return pos == -1 && *max_element(cnt.begin(), cnt.end()) > 1;
}
};
// Accepted
// 34/34 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 52.51 % of cpp submissions (7 MB)