Java:查找没有任何数字且至少有一个大写字符的最长子字符串

rog*_*hat 3 java string algorithm data-structures

遇到一个编程练习并被卡住了。问题是:

您需要为电子邮件定义一个有效的密码,但唯一的限制是:

  • 密码必须包含一个大写字符

  • 密码不能有数字

    现在,给定一个字符串,找到有效密码的最长子字符串的长度。例如Input Str = "a0Ba",输出应为 2,因为“Ba”是有效子字符串。

我使用了最长子字符串而不重复字符的概念,我之前已经这样做过,但无法修改它来找到上述问题的解决方案。我的不重复字符的最长子字符串的代码是:

public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    Set<Character> set = new HashSet<>();
    int ans = 0, i = 0, j = 0;
    while (i < n && j < n) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*iel 5

怎么样

final String input = "a0Ba";

final int answer = Arrays.stream(input.split("[0-9]+"))
    .filter(s -> s.matches("(.+)?[A-Z](.+)?"))
    .sorted((s1, s2) -> s2.length() - s1.length())
    .findFirst()
    .orElse("")
    .length();

out.println(answer);
Run Code Online (Sandbox Code Playgroud)

Arrays.stream(input.split("[0-9]+"))将原始字符串拆分为字符串数组。分隔符是任何数字序列(不允许使用数字,因此它们用作分隔符)。然后,创建一个流,以便我可以应用函数操作和转换。

.filter(s -> s.matches("(.+)?[A-Z](.+)?"))仅将至少包含一个大写字母的字符串保留到流中。

.sorted((s1, s2) -> s2.length() - s1.length())按长度 (desc) 对流进行排序。

.findFirst()尝试获取流的第一个字符串。

.orElse("")如果未找到字符串,则返回空字符串。

.length();获取字符串的长度。