LeetCode 1790. Check if One String Swap Can Make Strings Equal
原题链接在这里:https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/description/
题目:
You are given two strings s1
and s2
of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true
if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false
.
Example 1:
Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required.
Constraints:
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
ands2
consist of only lowercase English letters.
题解:
If two string lengths are different, then return false.
Have two indices to mark the two different positions.
If we see more than 2 indices different, return false.
If we find both indices, need to check both s1[ind0] == s2[ind1] and s1[ind1] == s2[ind0].
Time Complexity: O(n). n = s1.length().
Space: O(1).
AC Java:
1 class Solution { 2 public boolean areAlmostEqual(String s1, String s2) { 3 if(s1 == null && s2 == null){ 4 return true; 5 } 6 7 if(s1 == null || s2 == null || s1.length() != s2.length()){ 8 return false; 9 } 10 11 int n = s2.length(); 12 int ind0 = -1; 13 int ind1 = -1; 14 for(int i = 0; i < n; i++){ 15 if(s1.charAt(i) != s2.charAt(i)){ 16 if(ind0 == -1){ 17 ind0 = i; 18 }else if(ind1 == -1){ 19 ind1 = i; 20 }else{ 21 return false; 22 } 23 } 24 } 25 26 if(ind0 == -1 && ind1 == -1){ 27 return true; 28 } 29 30 if(ind1 == -1){ 31 return false; 32 } 33 34 return s1.charAt(ind0) == s2.charAt(ind1) && s1.charAt(ind1) == s2.charAt(ind0); 35 } 36 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2022-08-12 LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another
2022-08-12 LeetCode 1740. Find Distance in a Binary Tree
2022-08-12 LeetCode 2281. Sum of Total Strength of Wizards
2022-08-12 LeetCode 1710. Maximum Units on a Truck
2022-08-12 LeetCode 1567. Maximum Length of Subarray With Positive Product