My algorithm just iterates through s1 and s2 and checks the number of times s1[i] != s2[i]:
- if the number is equal to
0, then we can returntrueas the strings are identical- if the number is equal to
2, and the unequal characters were at index positionsiandj, then we just check thats1[index[0]] == s2[index[1]] && s1[index[1]] == s2[index[0]]- else, then we can always return
false
code
class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
int index[2];
int counter = 0;
for(int i = 0; i < s1.size(); ++i) {
if (s1[i] != s2[i]) {
if (counter == 2) {
return false;
}
index[counter] = i;
++counter;
}
}
if (counter == 0) {
return true;
}
else if (counter != 2) {
return false;
} else {
if (s1[index[0]] == s2[index[1]] and s1[index[1]] == s2[index[0]]) {
return true;
} else {
return false;
}
}
}
};
complexity
- Time:
O(n)- Space:
O(1)