LeetCode 1763. Longest Nice Substring

该问题是一个字符串处理算法题,目标是找到给定字符串中满足每个字母都有大小写出现的最长子串。使用分治策略,当遇到不满足条件的字符时,分别在该字符前后的子串中寻找最长优美子串,最后比较两者长度取较长者。代码示例给出了Java实现。
摘要由CSDN通过智能技术生成

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.

Constraints:

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

这题要求一个string里最长的substring,这个substring要满足的条件是里面的每一个char都同时有大小写出现。直观的想法就是双重for loop遍历所有的substring,每个substring看看是不是每个字符的大小写都出现在substring里。知道肯定有更好的解法但是想不到,看了答案以后惊觉这是divide and conquer。怎么想到d/c的呢,借鉴- LeetCode,大概是因为如果中间有一个字母不满足条件的话,只能查找它前后的substring了。

所以知道了思路以后其实很简单,先用一个set把所有char存进去,然后针对当前要check的string,从头到尾遍历,如果遇到一个字符它并没有大小写都出现,那就把它分成前后两部分分别求他们的longest nice substring,最后取前后两个里面更长的那个作为结果。

class Solution {
    public String longestNiceSubstring(String s) {
        if (s.length() < 2) {
            return "";
        }
        Set<Character> chars = new HashSet<>();
        for (char c : s.toCharArray()) {
            chars.add(c);
        }

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (chars.contains(Character.toLowerCase(c)) && chars.contains(Character.toUpperCase(c))) {
                continue;
            }
            String leftNiceSubstring = longestNiceSubstring(s.substring(0, i));
            String rightNiceSubstring = longestNiceSubstring(s.substring(i + 1, s.length()));
            return leftNiceSubstring.length() >= rightNiceSubstring.length() ? leftNiceSubstring : rightNiceSubstring;
        }
        return s;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值