Given two strings
Swapping letters is defined as taking two indices
A
and B
of lowercase letters, return true
if you can swap two letters in A
so the result is equal to B
, 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 A[i]
and A[j]
.Example 1:
Input: A = "ab", B = "ba"
Output: true
Approach
Java
public class BuddyStrings {public static void main(String[] args) {String A = "ab", B = "ba";System.out.println(buddyStrings(A, B));}static boolean buddyStrings(String A, String B) {int n = A.length();int m = B.length();if (n != m)return false;int i = 0;char c = 0, d = 0;for (i = 0; i < n; i++) {if (A.charAt(i) != B.charAt(i)) {c = B.charAt(i);d = A.charAt(i);break;}}if (i == n) {int f[] = new int[26];for (int k = 0; k < n; k++)f[A.charAt(k) - 'a']++;int flag = 0;for (int j = 0; j < 26; j++) {if (f[j] >= 2) {flag = 1;break;}}if (flag == 0)return false;return true;} else {int k;int flag1 = 0;for (k = i + 1; k < n; k++) {if (A.charAt(k) != B.charAt(k)) {if (A.charAt(k) == c && B.charAt(k) == d) {flag1 = 1;break;}}}int flag = 0;for (int l = k + 1; l < n; l++) {if (A.charAt(l) != B.charAt(l)) {flag = 1;break;}}if (flag == 0 && flag1 == 1)return true;return false;}}}
C++
#include <bits/stdc++.h>using namespace std;bool buddyStrings(string A, string B){int n = A.size();int m = B.size();if (n != m)return false;int i = 0;char c, d;for (i = 0; i < n; i++){if (A[i] != B[i]){c = B[i];d = A[i];break;}}if (i == n){int f[26] = {0};for (int k = 0; k < n; k++)f[A[k] - 'a']++;int flag = 0;for (int i = 0; i < 26; i++){if (f[i] >= 2){flag = 1;break;}}if (flag == 0)return false;return true;}else{int k;int flag1 = 0;for (k = i + 1; k < n; k++){if (A[k] != B[k]){if (A[k] == c && B[k] == d){flag1 = 1;break;}}}int flag = 0;for (int l = k + 1; l < n; l++){if (A[l] != B[l]){flag = 1;break;}}if (flag == 0 && flag1 == 1)return true;return false;}}int main(){string A = "ab", B = "ba";if (buddyStrings(A, B))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment