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.
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; } ListdiffIndex = 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每日一...
摘要:解题思路一道并不简单的模拟题,需要考虑的情况总结下来有三种长度不同返回完全相同且有重复字符返回字符串有不相等的两个地方需要查看它们交换后是否相等即可。 解题思路:...
摘要:记录长度法复杂度时间空间思路本题难点在于如何在合并后的字符串中,区分出原来的每一个子串。这里我采取的编码方式,是将每个子串的长度先赋在前面,然后用一个隔开长度和子串本身。这样我们先读出长度,就知道该读取多少个字符作为子串了。 Encode and Decode Strings Design an algorithm to encode a list of strings to a s...
摘要:最新更新思路和其他语言请访问哈希表法复杂度时间空间思路用一个哈希表记录字符串中字母到字符串中字母的映射关系,一个集合记录已经映射过的字母。或者用两个哈希表记录双向的映射关系。这里不能只用一个哈希表,因为要排除这种多对一的映射。 Isomorphic Strings 最新更新思路和其他语言请访问:https://yanjia.me/zh/2018/11/... Given two st...
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...
阅读 2746·2023-04-25 18:06
阅读 2510·2021-11-22 09:34
阅读 1675·2021-11-08 13:16
阅读 1277·2021-09-24 09:47
阅读 3028·2019-08-30 15:44
阅读 2745·2019-08-29 17:24
阅读 2567·2019-08-23 18:37
阅读 2422·2019-08-23 16:55