Cho hai chuỗi chữ thường S và T, tìm độ dài dãy con anagram dài nhất (các ký tự xuất hiện trong cả hai chuỗi, không cần liên tiếp).
Ví dụ: S = "helloworld", T = "hellorld" → kết quả 8.
Giải thuật (Đếm tần suất ký tự)
- Đếm tần suất ký tự trong
S→ dictc. - Đếm tần suất ký tự trong
T→ dictd. - Khởi tạo
res = 0. - Duyệt từng ký tự
chtrongc:- Nếu
có trongd:res += min(c[ch], d[ch]).
- Nếu
- Trả về
res.
Ví dụ minh họa
class Solution:
def solve(self, a, b):
c, d = {}, {}
for ch in a:
c[ch] = c.get(ch, 0) + 1
for ch in b:
d[ch] = d.get(ch, 0) + 1
res = 0
for ch in c:
if d.get(ch, 0) > 0:
res += min(c[ch], d[ch])
return res
ob = Solution()
S = "helloworld"
T = "hellorld"
print(ob.solve(S, T)) # Output: 8
Đầu vào
S = "helloworld", T = "hellorld"
Đầu ra
8