Java:查找不带任何数字和至少一个大写字符的最长子字符串
遇到一个编程练习,被卡住了。问题是: 您需要为电子邮件定义有效密码,但 限制包括:Java:查找不带任何数字和至少一个大写字符的最长子字符串,java,string,algorithm,data-structures,Java,String,Algorithm,Data Structures,遇到一个编程练习,被卡住了。问题是: 您需要为电子邮件定义有效密码,但 限制包括: 密码必须包含一个大写字符 密码不应包含数字 现在,给定一个字符串,找出最长子字符串的长度 是一个有效的密码。例如,对于输入Str=“a0Ba”,输出应 be 2,因为“Ba”是有效的子字符串 我使用了不重复字符的最长子字符串的概念,这是我之前已经做过的,但无法修改它来找到上述问题的解决方案。无重复字符的最长子字符串的代码为: public int lengthOfLongestSubstring(String
- 密码必须包含一个大写字符
- 密码不应包含数字
现在,给定一个字符串,找出最长子字符串的长度
是一个有效的密码。例如,对于
,输出应 be 2,因为“Ba”是有效的子字符串输入Str=“a0Ba”
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;
}
public int lengthOfLongestSubstring(字符串s){
int n=s.长度();
Set=newhashset();
int ans=0,i=0,j=0;
而(i
您可以使用一个简单的数组。使用的算法是动态滑动窗口。以下是静态滑动窗口的示例:
算法应如下所示:
跟踪char
数组的两个索引。这两个索引在这里称为front
和back
,表示数组的前面和后面
有一个int
(我在这里把它命名为up
)来跟踪大写字母char
的数量
将全部设置为0
如果front>N
其中N
是给定的char
数量,则使用while循环终止
如果下一个字符不是数字,请将1添加到front
。然后检查char
是否为大写。如果是,将1添加到up
如果up
至少为1,则在必要时更新最大长度
如果下一个字符是数字,则继续检查以下char
是否也是数字。将front
设置为char
不是数字的第一个索引,将back
设置为front-1
输出最大长度。我建议您将字符串拆分为一个没有数字的字符串数组:
yourString.split("[0-9]")
然后迭代该数组(表示数组a),以获得包含一个大写字符的最长字符串:
a[i].matches("[a-z]*[A-Z]{1}[a-z]*");
我正在使用Kadane算法的修改来搜索所需的密码长度。可以使用isNumeric()和isCaps()函数,也可以包含内联if语句。我已经在下面展示了函数
public boolean isNumeric(char x){
return (x>='0'&&x<='9');
}
public boolean isCaps(char x){
return (x>='A'&&x<='Z');
}
public int maxValidPassLen(String a)
{
int max_so_far = 0, max_ending_here = 0;
boolean cFlag = false;
int max_len = 0;
for (int i = 0; i < a.length(); i++)
{
max_ending_here = max_ending_here + 1;
if (isCaps(a.charAt(i))){
cFlag = true;
}
if (isNumeric(a.charAt(i))){
max_ending_here = 0;
cFlag = false;
}
else if (max_so_far<max_ending_here){
max_so_far = max_ending_here;
}
if(cFlag&&max_len<max_so_far){
max_len = max_so_far;
}
}
return max_len;
}
public boolean isNumeric(char x){
return(x>='0'&&x='A'&&x您不需要正则表达式。只需使用几个整数作为字符串的索引指针:
int i = 0;
int longestStart = 0;
int longestEnd = 0;
while (i < s.length()) {
// Skip past all the digits.
while (i < s.length() && Character.isDigit(s.charAt(i))) {
++i;
}
// i now points to the start of a substring
// or one past the end of the string.
int start = i;
// Keep a flag to record if there is an uppercase character.
boolean hasUppercase = false;
// Increment i until you hit another digit or the end of the string.
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
hasUppercase |= Character.isUpperCase(s.charAt(i));
++i;
}
// Check if this is longer than the longest so far.
if (hasUppercase && i - start > longestEnd - longestStart) {
longestEnd = i;
longestStart = start;
}
}
String longest = s.substring(longestStart, longestEnd);
inti=0;
int longestStart=0;
int longestEnd=0;
而(ilongestEnd-longestStart){
longestEnd=i;
longestStart=开始;
}
}
字符串最长=s.substring(longestStart,longestEnd);
虽然比正则表达式更详细,但这样做的优点是不创建任何不必要的对象:唯一创建的对象是最长的字符串,就在末尾。您可以使用我的解决方案,该解决方案在O(n)时间内运行,查找不带任何数字和大写字母的最长部分:
String testString = "skjssldfkjsakdfjlskdssfkjslakdfiop7adfaijsldifjasdjfil8klsasdfŞdijpfjapodifjpoaidjfpoaidjpfi9a";
int startIndex = 0;
int longestStartIndex = 0;
int endIndex = 0;
int index = 0;
int longestLength = Integer.MIN_VALUE;
boolean foundUpperCase = false;
while(index <= testString.length()) {
if (index == testString.length() || Character.isDigit(testString.charAt(index))) {
if (foundUpperCase && index > startIndex && index - startIndex > longestLength) {
longestLength = index - startIndex;
endIndex = index;
longestStartIndex = startIndex;
}
startIndex = index + 1;
foundUpperCase = false;
} else if (Character.isUpperCase(testString.charAt(index))) {
foundUpperCase = true;
}
index++;
}
System.out.println(testString.substring(longestStartIndex, endIndex));
String testString=“skjssldfkjsakdfjlskdssfkjslakdfiop7adfaijsldifjasdjfil8klsasdfŞdijpfjapodifjpoaidjfpoaidjpfi9a”;
int startIndex=0;
int longestStartIndex=0;
int-endIndex=0;
int指数=0;
int longestLength=Integer.MIN_值;
boolean foundUpperCase=false;
while(索引startIndex&&index-startIndex>longestLength){
longestLength=索引-startIndex;
endIndex=索引;
longestStartIndex=startIndex;
}
startIndex=指数+1;
foundUpperCase=false;
}else if(Character.isUpperCase(testString.charAt(index))){
foundUpperCase=true;
}
索引++;
}
System.out.println(testString.substring(longestStartIndex,endIndex));
这里有很多很好的答案,但我认为添加一个使用Java 8流的答案可能会很有趣:
IntStream.range(0, s.length()).boxed()
.flatMap(b -> IntStream.range(b + 1, s.length())
.mapToObj(e -> s.substring(b, e)))
.filter(t -> t.codePoints().noneMatch(Character::isDigit))
.filter(t -> t.codePoints().filter(Character::isUpperCase).count() == 1)
.mapToInt(String::length).max();
如果需要字符串(而不仅仅是长度),则最后一行可以替换为:
.max(Comparator.comparingInt(String::length));
它返回一个可选的我将使用流和可选的:
public static String getBestPassword(String password) throws Exception {
if (password == null) {
throw new Exception("Invalid password");
}
Optional<String> bestPassword = Stream.of(password.split("[0-9]"))
.filter(TypeErasure::containsCapital)
.sorted((o1, o2) -> o1.length() > o2.length() ? 1 : 0)
.findFirst();
if (bestPassword.isPresent()) {
return bestPassword.get();
} else {
throw new Exception("No valid password");
}
}
/**
* Returns true if word contains capital
*/
private static boolean containsCapital(String word) {
return word.chars().anyMatch(Character::isUpperCase);
}
public静态字符串getBestPassword(字符串密码)引发异常{
如果(密码==null){
抛出新异常(“无效密码”);
}
可选的bestPassword=Stream.of(password.split(“[0-9]”)
.filter(类型擦除::ContainesCapital)
.排序((o1,o2)->o1.length()>o2.length()?1:0)
.findFirst();
if(bestPassword.isPresent()){
返回bestPassword.get();
}否则{
抛出新异常(“无有效密码”);
}
}
/**
*如果word包含大写字母,则返回true
*/
私有静态布尔containsCapital(字符串字){
返回word.chars().anyMatch(字符::isUpperCase
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);
public String pass(String str){
int length = 0;
boolean uppercase = false;
String s= "";
String d= "";
for(int i=0;i<str.length();i++){
if(Character.isUpperCase(str.charAt(i)) == true){
uppercase = true;
s = s+str.charAt(i);
}else if(Character.isDigit(str.charAt(i)) == true ){
if(uppercase == true && s.length()>length){
d = s;
s = "";
length = s.length();
uppercase = false;
}
}else if(i==str.length()-1&&Character.isDigit(str.charAt(i))==false){
s = s + str.charAt(i);
if(uppercase == true && s.length()>length){
d = s;
s = "";
length = s.length();
uppercase = false;
}
}else{
s = s+str.charAt(i);
}
}
return d;}
def solution(str: String): Int = {
val strNoDigit = str.replaceAll("[0-9]", "-")
strAlphas = strNoDigit.split("-")
Try(strAlphas.filter(_.trim.find(_.isUpper).isDefined).maxBy(_.size))
.toOption
.map(_.length)
.getOrElse(-1)
}
def solution2(str: String): Int = {
val subSt = new ListBuffer[Char]
def checker(str: String): Unit = {
if (str.nonEmpty) {
val s = str.head
if (!s.isDigit) {
subSt += s
} else {
subSt += '-'
}
checker(str.tail)
}
}
checker(str)
if (subSt.nonEmpty) {
val noDigitStr = subSt.mkString.split("-")
Try(noDigitStr.filter(s => s.nonEmpty && s.find(_.isUpper).isDefined).maxBy(_.size))
.toOption
.map(_.length)
.getOrElse(-1)
} else {
-1
}
}
String[] s = testString.split("[0-9]");
int length = 0;
int index = -1;
for(int i=0; i< s.length; i++){
if(s[i].matches("[a-z]*.*[A-Z].*[a-z]*")){
if(length <= s[i].length()){
length = s[i].length();
index = i;
}
}
}
if(index >= 0){
System.out.println(s[index]);
}
public class LongestString {
public static void main(String[] args) {
// String testString = "AabcdDefghIjKL0";
String testString = "a0bb";
int startIndex = 0, endIndex = 0;
int previousUpperCaseIndex = -1;
int maxLen = 0;
for (; endIndex < testString.length(); endIndex++) {
if (Character.isUpperCase(testString.charAt(endIndex))) {
if (previousUpperCaseIndex > -1) {
maxLen = Math.max(maxLen, endIndex - startIndex);
startIndex = previousUpperCaseIndex + 1;
}
previousUpperCaseIndex = endIndex;
} else if (Character.isDigit(testString.charAt(endIndex))) {
if (previousUpperCaseIndex > -1) {
maxLen = Math.max(maxLen, endIndex - startIndex);
}
startIndex = endIndex + 1;
previousUpperCaseIndex = -1;
}
}
if (previousUpperCaseIndex > -1)
maxLen = Math.max(maxLen, endIndex - startIndex);
System.out.println(maxLen);
}}
String str = "a0Ba12hgKil8oPlk";
String[] str1 = str.split("[0-9]+");
List<Integer> in = new ArrayList<Integer>();
for (int i = 0; i < str1.length; i++) {
if (str1[i].matches("(.+)?[A-Z](.+)?")) {
in.add(str1[i].length());
} else {
System.out.println(-1);
}
}
Collections.sort(in);
System.out.println("string : " + in.get(in.size() - 1));
public static int validPassword(string str)
{
List<int> strLength = new List<int>();
if (!(str.All(Char.IsDigit)))
{
//string str = "a0Bb";
string[] splitStrs = str.Split(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
//check if each string contains a upper case
foreach (string s in splitStrs)
{
//Console.WriteLine(s);
if (s.Any(char.IsUpper) && s.Any(char.IsLower) || s.Any(char.IsUpper))
{
strLength.Add(s.Length);
}
}
if (strLength.Count == 0)
{
return -1;
}
foreach (int i in strLength)
{
//Console.WriteLine(i);
}
return strLength.Max();
}
else
{
return -1;
}
}
function ValidatePassword(password){
var doesContainNumber = false;
var hasUpperCase = false;
for(var i=0;i<password.length;i++){
if(!isNaN(password[i]))
doesContainNumber = true;
if(password[i] == password[i].toUpperCase())
hasUpperCase = true;
}
if(!doesContainNumber && hasUpperCase)
return true;
else
return false;
}
function GetLongestPassword(inputString){
var longestPassword = "";
for(var i=0;i<inputString.length-1;i++)
{
for (var j=i+1;j<inputString.length;j++)
{
var substring = inputString.substring(i,j+1);
var isValid = ValidatePassword(substring);
if(isValid){
if(substring.length > longestPassword.length)
{
longestPassword = substring;
}
}
}
}
if(longestPassword == "")
{
return "No Valid Password found";
}
else
{
return longestPassword;
}
}