🦁

LeetCode #1763 Longest Nice Substring

2024/10/23に公開

問題概要

入力値:s(string)
出力値:s(string)
Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
問題のリンク

入力例

Input: s = "YazaAay"
Output: "aAa"

解答例1

計算量:O(n)
Python

class Solution(object):
    def longestNiceSubstring(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) < 2: return ""

        ulSet = set(s)
        for i,c in enumerate(s):
            if c.swapcase() not in ulSet:
                s1 = self.longestNiceSubstring(s[0:i])
                s2 = self.longestNiceSubstring(s[i+1:])

                return s2 if len(s2) > len(s1) else s1
        return s
        

Runtime: 2ms
Beats: 99.53%

Discussion