Google Interview Question
SDE1sCountry: United States
private boolean areSameBySwap(String st1, String st2) {
if (st1.length() != st2.length()) return false;
int count = 0;
int prev = -1;
int cur = -1;
for (int i = 0; i < st1.length(); i++) {
if (st1.charAt(i) != st2.charAt(i)) {
count++;
if (count > 2) return false;
prev = cur;
cur = i;
}
}
return count == 2 &&
st1.charAt(prev) == st2.charAt(cur) &&
st1.charAt(cur) == st2.charAt(prev);
}
We can scan the strings and whenever we see a different char, build two arrays of diff. If the diff arrays become larger than 2, return false. If at the end of the scan the diff arrays contain 2 elements and swapping 2 elements in one diff array makes the diff array equal, return true.
The code below is for the follow up question.
- Alex December 07, 2017