领扣LintCode算法问题答案-1510. 亲密字符串

    科技2022-07-13  117

    领扣LintCode算法问题答案-1510. 亲密字符串

    目录

    1510. 亲密字符串描述样例 1:样例 2:样例 3:样例 4:样例 5: 题解鸣谢

    1510. 亲密字符串

    描述

    给定两个由小写字母构成的字符串A 和B,只要我们可以通过交换A中的两个字母得到与B相等的结果,就返回true;否则返回false。

    0 <= A.length <= 200000 <= A.length <= 20000A 和 B 仅由小写字母构成。

    样例 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

    题解

    public class Solution { /** * @param A: string A * @param B: string B * @return: bool */ public boolean buddyStrings(String A, String B) { // Write your code here if (A.length() != B.length()) { return false; } if (A.equals(B)) { int[] cs = new int[26]; for (char c : A.toCharArray()) { if (++cs[c - 97] > 1) { return true; } } return false; } int firstIndex = -1; for (int i = 0; i < A.length(); i++) { char c1 = A.charAt(i); char c2 = B.charAt(i); if (c1 != c2) { if (firstIndex == -1) { firstIndex = i; } else { char fc1 = A.charAt(firstIndex); char fc2 = B.charAt(firstIndex); if (fc1 != c2 || fc2 != c1) { return false; } } } } return true; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.014, SQL: 8