标签:and element else put [] letter wap ase boolean
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
wrong case: aa aa, ab cd, abc dew,
What a shame!
class Solution { public boolean buddyStrings(String A, String B) { int a1[] =new int[2]; int a2[] =new int[2]; if(A.length()!=B.length() || A.length()==0 || B.length()==0) return false; int count = 0; for(int i = 0; i<A.length(); i++){ if(A.charAt(i) != B.charAt(i)) { count++; if(count > 2) return false; a1[count-1] = A.charAt(i); a2[count-1] = B.charAt(i); } } if(count == 2 &&a1[0]==a2[1]&&a1[1]==a2[0]) return true; //case for aa (A==B and duplicate elements in the String) int index[] = new int[26]; if(A.equals(B)){ for(int i = 0; i<A.length(); i++){ index[A.charAt(i)-‘a‘]++; if(index[A.charAt(i)-‘a‘]>=2) return true; } return false; }else return false; } }
So many if else case to care about! Traps
859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**
标签:and element else put [] letter wap ase boolean
原文地址:https://www.cnblogs.com/stiles/p/Leetcode859.html