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 and s2 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 }

 

posted @ 2024-08-12 05:52  Dylan_Java_NYC  阅读(2)  评论(0编辑  收藏  举报