资讯专栏INFORMATION COLUMN

[LeetCode] 859. Buddy Strings

animabear / 1444人阅读

Problem

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

Note:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.

Solution
class Solution {
    public boolean buddyStrings(String A, String B) {
        if (A == null || B == null || A.length() != B.length()) return false;
        char[] s1 = A.toCharArray();
        char[] s2 = B.toCharArray();
        if (A.equals(B)) {
            int[] dict = new int[26];
            for (char ch: s1) {
                dict[ch-"a"]++;
                if (dict[ch-"a"] >= 2) return true;
            }
            return false;
        }
        
        List diffIndex = new ArrayList<>();
        for (int i = 0; i < s1.length; i++) {
            if (s1[i] != s2[i]) diffIndex.add(i);
        }
        if (diffIndex.size() != 2) return false;
        int i = diffIndex.get(0), j = diffIndex.get(1);
        if (A.charAt(i) == B.charAt(j) && A.charAt(j) == B.charAt(i)) return true;
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72543.html

相关文章

  • leetcode每日一题-859:亲密字符串

    摘要:每日一题亲密字符串链接亲密字符串题目分析题目本身不是很难,但是有不少需要注意的地方,逐一来进行分析。首先如果两个字符串不一样长,那么肯定是。 leetcode每日一...

    张迁 评论0 收藏0
  • LeetCode 859 亲密字符串[模拟] HERODING的LeetCode之路

    摘要:解题思路一道并不简单的模拟题,需要考虑的情况总结下来有三种长度不同返回完全相同且有重复字符返回字符串有不相等的两个地方需要查看它们交换后是否相等即可。 解题思路:...

    aisuhua 评论0 收藏0
  • [Leetcode] Encode and Decode Strings 字符串编解码

    摘要:记录长度法复杂度时间空间思路本题难点在于如何在合并后的字符串中,区分出原来的每一个子串。这里我采取的编码方式,是将每个子串的长度先赋在前面,然后用一个隔开长度和子串本身。这样我们先读出长度,就知道该读取多少个字符作为子串了。 Encode and Decode Strings Design an algorithm to encode a list of strings to a s...

    gself 评论0 收藏0
  • [Leetcode] Isomorphic Strings 同构字符串

    摘要:最新更新思路和其他语言请访问哈希表法复杂度时间空间思路用一个哈希表记录字符串中字母到字符串中字母的映射关系,一个集合记录已经映射过的字母。或者用两个哈希表记录双向的映射关系。这里不能只用一个哈希表,因为要排除这种多对一的映射。 Isomorphic Strings 最新更新思路和其他语言请访问:https://yanjia.me/zh/2018/11/... Given two st...

    antz 评论0 收藏0
  • [LeetCode] 205. Isomorphic Strings

    Problem Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with an...

    graf 评论0 收藏0

发表评论

0条评论

animabear

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<