親密字符串----leetcode

給定兩個由小寫字母構成的字符串 A 和 B ,只要我們可以通過交換 A 中的兩個字母得到與 B 相等的結果,就返回 true ;否則返回 false 。

 

示例 1:

輸入: A = "ab", B = "ba"
輸出: true

示例 2:

輸入: A = "ab", B = "ab"
輸出: false

示例 3:

輸入: A = "aa", B = "aa"
輸出: true

示例 4:

輸入: A = "aaaaaaabc", B = "aaaaaaacb"
輸出: true

示例 5:

輸入: A = "", B = "aa"
輸出: false

 

提示:

  1. 0 <= A.length <= 20000
  2. 0 <= B.length <= 20000
  3. A 和 B 僅由小寫字母構成。

AC代碼:

class Solution {
    public boolean buddyStrings(String A, String B) {
        Map<Character,Integer>map=new HashMap<Character,Integer>();
         if(A.length()!=B.length())return false;
         int x1=-1,x2=-1;
         int flag=0;
         for(int i=0;i<A.length();i++){ 
             if(A.charAt(i)!=B.charAt(i)){
                 flag++;
                 if(x1!=-1)x2=i;
                 else x1=i;
             }
         }
         if(flag==2){
             if(A.charAt(x1)==B.charAt(x2)&&A.charAt(x2)==B.charAt(x1))
                 return true;
             else
                 return false;
         }
         else if(flag==0){
             for(int i=0;i<A.length();i++){
                 if(map.get(Character.valueOf(A.charAt(i)))!=null){
                     return true;
                 }
                 else
                     map.put(Character.valueOf(A.charAt(i)),1);
             }
             return false;
         }
         else return false;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章