Re: [閒聊] 每日LeetCode
看板Marginalman作者JerryChungYC (JerryChung)時間5月前 (2024/01/13 09:08)推噓1(1推 0噓 0→)留言1則, 1人參與討論串600/719 (看更多)
https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-
anagram
1347. Minimum Number of Steps to Make Two Strings Anagram
給兩個長度相同的字串s和t,每次可以從t選一個字元換成其他字,求把t變成s的最小次數
只要包含的字元相同就好,順序可以不同(Anagram)。
Example 1:
Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.
Example 2:
Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters
to make t anagram of s.
Example 3:
Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams.
Python3 Code:
---------------------------------------------------
class Solution:
def minSteps(self, s: str, t: str) -> int:
if len(set(s)) == len(set(t)) == 1 and set(s) != set(t):
return len(s)
sl = list(s)
for word in t:
if word in sl:
sl.remove(word)
return len(sl)
---------------------------------------------------
這個的結果是
https://i.imgur.com/NAr23we.png
後來換了個解法
---------------------------------------------------
class Solution:
def minSteps(self, s: str, t: str) -> int:
for word in set(t):
s = s.replace(word, '', t.count(word))
return len(s)
---------------------------------------------------
https://i.imgur.com/1zfQsN3.png
好耶 Memory就不管了 沒救
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.28.204 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1705108133.A.7F4.html
推
01/13 09:09,
5月前
, 1F
01/13 09:09, 1F
討論串 (同標題文章)