【发布时间】:2017-01-16 05:54:14
【问题描述】:
遇到了一个编程练习并被卡住了。问题是:
您需要为电子邮件定义一个有效的密码,但唯一的 限制是:
密码必须包含一个大写字符
密码不能有数字
现在,给定一个字符串,找出最长的子字符串的长度 是一个有效的密码。例如
Input Str = "a0Ba",输出应该 be 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;
}
【问题讨论】:
-
如果您想以优雅的方式进行操作,请使用
regex。在谷歌上搜索Pattern.matches()和正则表达式。
标签: java string algorithm data-structures