下面是一个快速,肮脏,未优化(可能是越野车),但你想要实现什么样的独立示例。
public static void main(String[] args) {
// should not allow
System.out.println(hasValidSequence("abcd", 3));
// should not allow
System.out.println(hasValidSequence("1234", 3));
// should allow
System.out.println(hasValidSequence("abcd", 4));
// should allow
System.out.println(hasValidSequence("1234", 4));
}
public static boolean hasValidSequence(String input, int maxAllowed) {
// boilerplate validation of empties/nulls
if (input == null || input.isEmpty()) {
// TODO handle better?
return false;
}
// counter for blowing things up if reached
int counter = 0;
// char takes int values - initializing as bogus 0
char c = (char)0;
// iterating input String characters one by one
for (int i = 0; i < input.length(); i++) {
// previous char is next char as int, - 1 --> they're successive
// you can fool around and replace with input.charAt(i) <= i
// for indirect sequences or same characters
// TODO check it's an alpha numeric!
if (c == input.charAt(i) - 1) {
// incrementing counter
counter++;
}
// assigning current char
c = input.charAt(i);
// counter reached? we blow things up!
if (counter == maxAllowed) {
return false;
}
}
// no counter reached, return true
return true;
}
输出
false
false
true
true