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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/72543.html
摘要:每日一題親密字符串鏈接親密字符串題目分析題目本身不是很難,但是有不少需要注意的地方,逐一來(lái)進(jìn)行分析。首先如果兩個(gè)字符串不一樣長(zhǎng),那么肯定是。 leetcode每日一...
摘要:解題思路一道并不簡(jiǎn)單的模擬題,需要考慮的情況總結(jié)下來(lái)有三種長(zhǎng)度不同返回完全相同且有重復(fù)字符返回字符串有不相等的兩個(gè)地方需要查看它們交換后是否相等即可。 解題思路:...
摘要:記錄長(zhǎng)度法復(fù)雜度時(shí)間空間思路本題難點(diǎn)在于如何在合并后的字符串中,區(qū)分出原來(lái)的每一個(gè)子串。這里我采取的編碼方式,是將每個(gè)子串的長(zhǎng)度先賦在前面,然后用一個(gè)隔開長(zhǎng)度和子串本身。這樣我們先讀出長(zhǎng)度,就知道該讀取多少個(gè)字符作為子串了。 Encode and Decode Strings Design an algorithm to encode a list of strings to a s...
摘要:最新更新思路和其他語(yǔ)言請(qǐng)?jiān)L問(wèn)哈希表法復(fù)雜度時(shí)間空間思路用一個(gè)哈希表記錄字符串中字母到字符串中字母的映射關(guān)系,一個(gè)集合記錄已經(jīng)映射過(guò)的字母。或者用兩個(gè)哈希表記錄雙向的映射關(guān)系。這里不能只用一個(gè)哈希表,因?yàn)橐懦@種多對(duì)一的映射。 Isomorphic Strings 最新更新思路和其他語(yǔ)言請(qǐng)?jiān)L問(wèn):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...
閱讀 2805·2023-04-25 18:06
閱讀 2594·2021-11-22 09:34
閱讀 1693·2021-11-08 13:16
閱讀 1317·2021-09-24 09:47
閱讀 3058·2019-08-30 15:44
閱讀 2783·2019-08-29 17:24
閱讀 2594·2019-08-23 18:37
閱讀 2445·2019-08-23 16:55