版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82877863
Description:
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
Example 2:
Input: A = "ab", B = "ab"
Output: false
Example 3:
Input: A = "aa", B = "aa"
Output: true
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:
Input: A = "", B = "aa"
Output: false
Note:
- 0 <= A.length <= 20000
- 0 <= B.length <= 20000
- A and B consist only of lowercase letters.
题意:给定两个字符串A和B,判断能够将A中的两个字符交换使得A与B相等;
解法一(超时):最简单的做法就是遍历A所有可能的交换方式,判断是否有一种可以满足交换后A与B相等的情况;
Java
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) {
return false;
}
for (int i = 0; i < A.length() - 1; i++) {
for (int j = i + 1; j < A.length(); j++) {
StringBuilder sb = new StringBuilder(A);
sb.replace(i, i + 1, "" + A.charAt(j));
sb.replace(j, j + 1, "" + A.charAt(i));
if (sb.toString().equals(B)) {
return true;
}
}
}
return false;
}
}
解法二:我们需要考虑两种情况
- 第一种如果A.equals(B),要相令A交换两个字符后还是与B相等,那么A中至少有一个字符出现两次,这样交换前后A不变
- 第二种如果A与B不相等,那么我们就可以找到A中从首部开始出现的第一个与B相同位置但不相等的字符(即A[i] != B[i], 0 <= i < A.length());之后,我们需要从这个位置往后找出A中与B[i]相等的字符进行交换(即A[j] == B[i], i < j < A.length()),判断交换后是否相等,一直到判断完所有这个位置之后A中与B[i]相等的字符;
Java
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length() || A.length() == 0) {
return false;
}
if (A.equals(B)) {
int[] letter = new int[26];
for (int i = 0; i < A.length(); i++) {
letter[A.charAt(i) - 'a'] += 1;
if (letter[A.charAt(i) - 'a'] > 1) return true;
}
return false;
}
int index = 0;
while (index < A.length() && A.charAt(index) == B.charAt(index)) {
index++;
}
for (int i = index + 1; i < A.length(); i++) {
if (A.charAt(i) == B.charAt(index)) {
StringBuilder sb = new StringBuilder(A);
sb.replace(index, index + 1, "" + A.charAt(i));
sb.replace(i, i + 1, "" + A.charAt(index));
if (sb.toString().equals(B)) {
return true;
}
}
}
return false;
}
}