"""Blind 75, String section (10 problems)."""
from collections import Counter, defaultdict
from typing import List


def length_of_longest_substring(s: str) -> int:
    """LC 3. Sliding window; on a repeat, jump the left edge past that character's last position."""
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if last.get(ch, -1) >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best


def character_replacement(s: str, k: int) -> int:
    """LC 424. A window is valid if its length minus its most common letter count is <= k.
    The max count never needs to shrink: the answer only grows when a bigger count appears."""
    counts: Counter = Counter()
    left = top = 0
    for right, ch in enumerate(s):
        counts[ch] += 1
        top = max(top, counts[ch])
        if right - left + 1 - top > k:
            counts[s[left]] -= 1
            left += 1
    return len(s) - left


def min_window(s: str, t: str) -> str:
    """LC 76. Expand right until every needed char is covered, then shrink left while it stays covered."""
    need = Counter(t)
    missing = len(t)
    left = 0
    best = (0, float("inf"))
    for right, ch in enumerate(s, 1):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1
        if missing == 0:
            while need[s[left]] < 0:
                need[s[left]] += 1
                left += 1
            if right - left < best[1] - best[0]:
                best = (left, right)
            need[s[left]] += 1
            missing += 1
            left += 1
    return "" if best[1] == float("inf") else s[best[0]:best[1]]


def is_anagram(s: str, t: str) -> bool:
    """LC 242. Same letters with the same counts."""
    return Counter(s) == Counter(t)


def group_anagrams(strs: List[str]) -> List[List[str]]:
    """LC 49. Anagrams share a key: the sorted word (or a 26-letter count tuple)."""
    groups = defaultdict(list)
    for w in strs:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())


def is_valid_parentheses(s: str) -> bool:
    """LC 20. Push openers; every closer must match the top of the stack."""
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack


def is_palindrome(s: str) -> bool:
    """LC 125. Two pointers that skip non-alphanumerics and compare lowercase letters."""
    l, r = 0, len(s) - 1
    while l < r:
        if not s[l].isalnum():
            l += 1
        elif not s[r].isalnum():
            r -= 1
        elif s[l].lower() != s[r].lower():
            return False
        else:
            l, r = l + 1, r - 1
    return True


def _expand(s: str, l: int, r: int):
    while l >= 0 and r < len(s) and s[l] == s[r]:
        l, r = l - 1, r + 1
    return l + 1, r  # s[l+1:r] is the palindrome


def longest_palindrome(s: str) -> str:
    """LC 5. Expand around each of the 2n-1 centres (letters and gaps between letters)."""
    best = (0, 0)
    for i in range(len(s)):
        for l, r in (_expand(s, i, i), _expand(s, i, i + 1)):
            if r - l > best[1] - best[0]:
                best = (l, r)
    return s[best[0]:best[1]]


def count_substrings(s: str) -> int:
    """LC 647. Same centre expansion; each successful step outward is one more palindrome."""
    total = 0
    for i in range(len(s)):
        for l, r in ((i, i), (i, i + 1)):
            while l >= 0 and r < len(s) and s[l] == s[r]:
                total += 1
                l, r = l - 1, r + 1
    return total


def encode(strs: List[str]) -> str:
    """LC 271 (Premium). Length-prefix each string ("5#hello"), so any character, even '#', is safe."""
    return "".join(f"{len(w)}#{w}" for w in strs)


def decode(data: str) -> List[str]:
    """LC 271 (Premium). Read digits up to '#', then take exactly that many characters."""
    out, i = [], 0
    while i < len(data):
        j = data.index("#", i)
        size = int(data[i:j])
        out.append(data[j + 1:j + 1 + size])
        i = j + 1 + size
    return out
