码迷,mamicode.com
首页 > 其他好文 > 详细

859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**

时间:2018-07-10 13:42:16      阅读:180      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!