Letters swapping - LeetCode

description:

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 0 and 2 in "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 * 104

s and goal consist of lowercase letters.

My code:



public class Solution {

public bool BuddyStrings(string s, string goal) {

int total = s.Length;

int same = 0;

List<char> different = new List<char>();

if(s.Length != goal.Length){

return false;

}

for(int i=0; i < total; i++){

if(s[i] == goal[i]){

same++;

}

else{

different.Add(s[i]);

different.Add(goal[i]);

}

}

if(same == total-2 && total !=2){

if(different[0]==different[3] && different[1] == different[2]){

return true;

}

else{

//Console.WriteLine(different[0]);

//Console.WriteLine(different[1]);

//Console.WriteLine(different[2]);

//Console.WriteLine(different[3]);

return false;

}

}

else if(same == total && total !=2){

for(int i = 0;i<total-1; i ++){

for(int j=i+1;j<total;j++){

if(s[i]==s[j]){

return true;

break;

}

}

}

return false;

}

else if (same == 0 && total == 2){

if(s[0]==goal[1] && s[1]==goal[0] ){

return true;

}

else

return false;

}

else if (same == 2 && total == 2){

if(s[0]!=s[1]){

return false;

}

else

return true;

}

else{

//Console.WriteLine(same);

//Console.WriteLine(total);

return false;

}

}

}

Next
Next

Processing a “locale” file with Python (Copy)