Skip to content

Commit 7e37175

Browse files
committed
[LeetCode Sync] Runtime - 3 ms (42.52%), Memory - 18 MB (46.41%)
1 parent cf7fb0f commit 7e37175

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>Given two strings <code>s</code> and <code>goal</code>, return <code>true</code><em> if you can swap two letters in </em><code>s</code><em> so the result is equal to </em><code>goal</code><em>, otherwise, return </em><code>false</code><em>.</em></p>
2+
3+
<p>Swapping letters is defined as taking two indices <code>i</code> and <code>j</code> (0-indexed) such that <code>i != j</code> and swapping the characters at <code>s[i]</code> and <code>s[j]</code>.</p>
4+
5+
<ul>
6+
<li>For example, swapping at indices <code>0</code> and <code>2</code> in <code>&quot;abcd&quot;</code> results in <code>&quot;cbad&quot;</code>.</li>
7+
</ul>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> s = &quot;ab&quot;, goal = &quot;ba&quot;
14+
<strong>Output:</strong> true
15+
<strong>Explanation:</strong> You can swap s[0] = &#39;a&#39; and s[1] = &#39;b&#39; to get &quot;ba&quot;, which is equal to goal.
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> s = &quot;ab&quot;, goal = &quot;ab&quot;
22+
<strong>Output:</strong> false
23+
<strong>Explanation:</strong> The only letters you can swap are s[0] = &#39;a&#39; and s[1] = &#39;b&#39;, which results in &quot;ba&quot; != goal.
24+
</pre>
25+
26+
<p><strong class="example">Example 3:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> s = &quot;aa&quot;, goal = &quot;aa&quot;
30+
<strong>Output:</strong> true
31+
<strong>Explanation:</strong> You can swap s[0] = &#39;a&#39; and s[1] = &#39;a&#39; to get &quot;aa&quot;, which is equal to goal.
32+
</pre>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Constraints:</strong></p>
36+
37+
<ul>
38+
<li><code>1 &lt;= s.length, goal.length &lt;= 2 * 10<sup>4</sup></code></li>
39+
<li><code>s</code> and <code>goal</code> consist of lowercase letters.</li>
40+
</ul>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def buddyStrings(self, s: str, goal: str) -> bool:
3+
m, n = len(s), len(goal)
4+
if m != n:
5+
return False
6+
7+
count_s, count_goal = Counter(s), Counter(goal)
8+
if count_s != count_goal:
9+
return False
10+
11+
diff = sum(s[i] != goal[i] for i in range(n))
12+
return diff == 2 or (diff == 0 and any(val > 1 for val in count_s.values()))

0 commit comments

Comments
 (0)