LeetCode 0854. K-Similar Strings Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0854. K-Similar Strings

Description

Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.

Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.

 

Example 1:

Input: s1 = "ab", s2 = "ba"
Output: 1
Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba".

Example 2:

Input: s1 = "abc", s2 = "bca"
Output: 2
Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".

 

Constraints:

  • 1 <= s1.length <= 20
  • s2.length == s1.length
  • s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
  • s2 is an anagram of s1.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def kSimilarity(self, s1: str, s2: str) -> int: def next(s): i = 0 while s[i] == s2[i]: i += 1 res = [] for j in range(i + 1, n): if s[j] == s2[i] and s[j] != s2[j]: res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) return res q = deque([s1]) vis = {s1} ans, n = 0, len(s1) while 1: for _ in range(len(q)): s = q.popleft() if s == s2: return ans for nxt in next(s): if nxt not in vis: vis.add(nxt) q.append(nxt) ans += 1(code-box)

Solution 2

PythonJavaC++Go
class Solution: def kSimilarity(self, s1: str, s2: str) -> int: def f(s): cnt = sum(c != s2[i] for i, c in enumerate(s)) return (cnt + 1) >> 1 def next(s): i = 0 while s[i] == s2[i]: i += 1 res = [] for j in range(i + 1, n): if s[j] == s2[i] and s[j] != s2[j]: res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) return res q = [(f(s1), s1)] dist = {s1: 0} n = len(s1) while 1: _, s = heappop(q) if s == s2: return dist[s] for nxt in next(s): if nxt not in dist or dist[nxt] > dist[s] + 1: dist[nxt] = dist[s] + 1 heappush(q, (dist[nxt] + f(nxt), nxt))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !