到目前为止,我已编写此代码以检查字符串是否具有连续的升序或降序字符。 这些是不变量,标记输入是否连续 字符串,如89012或 xyZabc将计为连续。另一方面,09283dgdDDf不算作连续。 拐角情况如AbCBa或1abC应该返回false。另一方面,DcbaZ应该返回true
请注意,到目前为止,我的代码仅用于角色部分,请帮助此noob使其正常工作。我有错误
import java.util.Scanner;
public class generalizedorder {
public static void main(String[] args)
{
java.util.Scanner reader = new java.util.Scanner(System.in);
System.out.println("Enter the string");
String s = reader.next();
}
public boolean checkForAscendingOrDescendingPart(String s, int l)
{
for (int i = 0; i <= s.length() - l; ++i)
{
boolean success = true;
char c = s.charAt(i);
for (int j = 1; j < l; ++j)
{
if (((char) c + j) != s.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
success = true;
for (int j = 1; j < l; ++j)
{
if (((char) c - j) != s.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
}
return false;
}}
system.out.println(checkForAscendingOrDescendingPart);
}}
答案 0 :(得分:0)
我做了以下假设(根据您的描述):
所以,你可以通过从头到尾迭代,将n
允许的最大连续出现考虑在内并进行简单的计算来实现:
连续出现ASCI差异为“1”的字符。 (无论是否定的还是积极的)。 由于你想把“abc”和“cba”连续输入,常见的事情是:他们的ASCI差异的总和将是2或减2.如果你想要使用“4个字符”,总和将是3或者减去3.
1
2
-2
2
因此,在比较连续字符时,您不希望点击|n-1|
,其中n
是连续字符的最大允许出现次数:
public boolean isConsecutive(String stringToTest, int n) {
int sumOfDifferences = 0;
int lastTemp = 0;
Boolean consecutive = false;
for (int i = 0; i < stringToTest.length() - 1; i++) {
// Whenever the difference is 1 or minues 1, add it to sumOfDifferences.
// when sumOfDifferences= |max -1| -> break: consecutive!
// when difference > 1 or difference < -1 : Reset sumOfDifferences.
// when temp != lastTemp : Reset sumOfDifferences.
int temp = stringToTest.charAt(i) - stringToTest.charAt(i + 1);
if (temp != lastTemp) {
// ASCI directon change. reset. Otherwhise 214 will be consecutive. when comparing for 3 characters. (sumOfdifference would be 2 (-1 + 3)
sumOfDifferences = 0;
}
if (temp == 1 || temp == -1) {
sumOfDifferences += temp;
} else {
// way off. reset.
sumOfDifferences = 0;
}
// sumOfDiff == |n-1| ?
if (sumOfDifferences == n - 1 || sumOfDifferences == ((n - 1) * -1)) {
consecutive = true;
break;
}
lastTemp = temp;
}
return consecutive;
}
以下测试结果是肯定的:
@Test
public void testcons() {
assertEquals(true, isConsecutive("89012", 3));
assertEquals(true, isConsecutive("xyZabc", 3));
assertEquals(false, isConsecutive("09283dgdDDf", 3));
assertEquals(false, isConsecutive("AbCBa", 3));
assertEquals(false, isConsecutive("1abC", 3));
assertEquals(true, isConsecutive("DcbaZ", 3));
assertEquals(true, isConsecutive("ab", 2));
assertEquals(true, isConsecutive("abc", 3));
assertEquals(true, isConsecutive("abcd", 4));
assertEquals(true, isConsecutive("abcde", 5));
assertEquals(true, isConsecutive("abcdef", 6));
}
这适用于:数字和字母字符串。 (即使是字母数字,但如果你不想这样,你可以提前排除它们)