zoukankan      html  css  js  c++  java
  • 859. Buddy Strings

    Question

    859. Buddy Strings

    Solution

    题目大意:

    两个字符串,其中一个字符串任意两个字符互换后与另一个字符串相等,只能互换一次

    思路:

    diff 记录不同字符数
    
    两个字符串长度不同 return false
    
    两个字符串长度相同:
    abc abd     无重复,diff == 1  ca[3] != cb[3] return false
    abc abc     无重复,diff == 0  return false
    ab ba       无重复,diff == 2  return true
    aa aa       aa重复,diff == 0  return true
    aabc aabc   aa重复,diff == 0  return true
    aacb aabc   aa重复,diff == 2  return true
    

    Java实现:

    public boolean buddyStrings(String A, String B) {
        if (A.length() != B.length()) return false;
        int[] ca = new int[26];
        int[] cb = new int[26];
        int diff = 0;
        for (int i = 0; i < A.length(); i++) {
            ca[A.charAt(i) - 'a']++;
            cb[B.charAt(i) - 'a']++;
            if (A.charAt(i) != B.charAt(i)) diff++;
        }
        for (int i = 0; i < ca.length; i++) {
            if (diff == 0 && ca[i] > 1) return true;
            if (ca[i] != cb[i]) return false;
        }
        return diff == 2;
    }
    
  • 相关阅读:
    2019.8.15刷题统计
    2019.8.12刷题统计
    2019.8.11刷题统计
    2019.8.10刷题统计
    2019.8.9刷题统计
    2019.8.8刷题统计
    2019.8.7刷题统计
    2019.8.6刷题统计
    xuezhan.org 6.28
    xuezhan.org 6.27
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9532321.html
Copyright © 2011-2022 走看看