Skip to content

Commit 139d807

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (47.15%)
1 parent b858f3a commit 139d807

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<p>You are given two strings <code>s1</code> and <code>s2</code> of equal length. A <strong>string swap</strong> is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.</p>
2+
3+
<p>Return <code>true</code> <em>if it is possible to make both strings equal by performing <strong>at most one string swap </strong>on <strong>exactly one</strong> of the strings. </em>Otherwise, return <code>false</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> s1 = &quot;bank&quot;, s2 = &quot;kanb&quot;
10+
<strong>Output:</strong> true
11+
<strong>Explanation:</strong> For example, swap the first character with the last character of s2 to make &quot;bank&quot;.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> s1 = &quot;attack&quot;, s2 = &quot;defend&quot;
18+
<strong>Output:</strong> false
19+
<strong>Explanation:</strong> It is impossible to make them equal with one string swap.
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> s1 = &quot;kelb&quot;, s2 = &quot;kelb&quot;
26+
<strong>Output:</strong> true
27+
<strong>Explanation:</strong> The two strings are already equal, so no string swap operation is required.
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
<p><strong>Constraints:</strong></p>
32+
33+
<ul>
34+
<li><code>1 &lt;= s1.length, s2.length &lt;= 100</code></li>
35+
<li><code>s1.length == s2.length</code></li>
36+
<li><code>s1</code> and <code>s2</code> consist of only lowercase English letters.</li>
37+
</ul>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Approach 2: Only Check Differences
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def areAlmostEqual(self, s1: str, s2: str) -> bool:
8+
first_index_diff = 0
9+
second_index_diff = 0
10+
num_diffs = 0
11+
12+
for i in range(len(s1)):
13+
if s1[i] != s2[i]:
14+
num_diffs += 1
15+
16+
if num_diffs > 2:
17+
return False
18+
elif num_diffs == 1:
19+
first_index_diff = i
20+
else:
21+
second_index_diff = i
22+
23+
return (
24+
s1[first_index_diff] == s2[second_index_diff] and
25+
s1[second_index_diff] == s2[first_index_diff]
26+
)
27+
28+

0 commit comments

Comments
 (0)