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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 2784·2023-04-25 18:06
閱讀 2576·2021-11-22 09:34
閱讀 1684·2021-11-08 13:16
閱讀 1302·2021-09-24 09:47
閱讀 3049·2019-08-30 15:44
閱讀 2773·2019-08-29 17:24
閱讀 2584·2019-08-23 18:37
閱讀 2433·2019-08-23 16:55