美文网首页
[Java] LeetCode 859. Buddy Strin

[Java] LeetCode 859. Buddy Strin

作者: 葵sunshine | 来源:发表于2019-04-05 00:59 被阅读0次

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 = "", B = "aa"
Output: false

问 :String A 是否能通过交换2个字符的位置使 String A 的内容和 String B 相同。

Solution

  1. 分情况讨论:A和B长度不等、A和B内容相等、A和B内容不等
  2. 若A、B长度不同,返回 false;
  3. 若A、B内容相同,则统计A中是否有重复字符,若有,则可交换相同字符,使A不变,返回 true;
  4. 若A、B内容不等,统计A和B字符不等的位置,判断个数是否为2,是否在对应交换的位置上字符相等。
class Solution {
   boolean buddyStrings(String A, String B) {
        if (A.length() != B.length())
            return false;
        if(A.equals(B)){
            Set<Character> set = new HashSet<>();
            for(char c : A.toCharArray())
                set.add(c);
            return set.size() < A.length();
        }
       List<Integer> dif = new ArrayList<>();
       for(int i = 0;i<A.length();i++)
           if(A.charAt(i) !=B.charAt(i)) dif.add(i);
       return dif.size() == 2 && A.charAt(dif.get(0) )==B.charAt(dif.get(1)) 
                     && A.charAt(dif.get(1)) ==B.charAt(dif.get(0));
    }
}

解法参考

相关文章

网友评论

      本文标题:[Java] LeetCode 859. Buddy Strin

      本文链接:https://www.haomeiwen.com/subject/ueociqtx.html