A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not.

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.

 

Example 1:

Input: s = "YazaAay"
Output: "aAa"
Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
"aAa" is the longest nice substring.
Example 2:

Input: s = "Bb"
Output: "Bb"
Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.
Example 3:

Input: s = "c"
Output: ""
Explanation: There are no nice substrings.
Example 4:

Input: s = "dDzeE"
Output: "dD"
Explanation: Both "dD" and "eE" are the longest nice substrings.
As there are multiple longest nice substrings, return "dD" since it occurs earlier.
 

Constraints:

1 <= s.length <= 100
s consists of uppercase and lowercase English letters.

这题初看起来感觉有点难,想了半天有没有什么好的解法去解,想了半天想不出来,心想不会去爆破吧。后来实在没办法,Show hint了一下,结果是爆破。。。

爆破没啥好说的,看看子串是否符合条件即可,取大的子串。


class LongestNiceSubstring : public Solution {
public:
    void Exec() {

    }
    string longestNiceSubstring(string s) {
        string res;
        for (int i = 0; i < s.size(); i++) {
            char counters[26] = {0};
            for (int j = i; j < s.size(); j++) {
                if (s[j] >= 'a') counters[s[j] - 'a'] |= 0x01;
                else counters[s[j] - 'A'] |= 0x02;
                if (j - i + 1 > 1) {
                    bool valid = true;
                    for (int k = 0; k < 26; k++) {
                        if (counters[k] != 0 && counters[k] != 3) {
                            valid = false;
                            break;
                        }
                    }
                    if (valid && j - i + 1 > res.size()) res = s.substr(i, j - i + 1);
                }
            }
        }
        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day