[Geeks for Geeks] Meta Strings

Meta Strings

Given two strings consisting of lowercase english alphabets, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool metaStrings (string S1, string S2)
{
if(S1.length() != S2.length()) return false;
vector<char> diff1, diff2;
int diff = 0, n = S1.length();
for(int i = 0; i < n and diff <= 2; i++) {
if(S1[i] != S2[i]) {
diff++;
diff1.push_back(S1[i]);
diff2.push_back(S2[i]);
}
}
return diff == 2 and diff1[0] == diff2[1] and diff2[0] == diff1[1];
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/meta-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.