-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbuddyStrings.cpp
More file actions
45 lines (41 loc) · 1.08 KB
/
buddyStrings.cpp
File metadata and controls
45 lines (41 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//question link: https://leetcode.com/problems/buddy-strings/
//code:
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool buddyStrings(string A, string B) {
if(A.length() != B.length()) {
return false;
}
bool sameCharsPresent = false;
unordered_map<char, int> freq;
for(char ch: A) {
freq[ch]++;
if(freq[ch] > 1) {
sameCharsPresent = true;
}
}
// to check if different chars or chars with different freq present
for(char ch: B) {
if(freq.count(ch) && freq[ch] > 0) {
freq[ch]--;
} else {
return false;
}
}
int misplacedChars = 0;
for(int i=0; i<A.length(); i++) {
if(A[i] != B[i]) {
misplacedChars++;
}
}
if(misplacedChars == 2) {
return true;
} else if(misplacedChars == 0 && sameCharsPresent) {
return true;
} else {
return false;
}
}
};