![](/img/trans.png)
[英]How to get all the possible sequences of x characters from a string of n characters in java
[英]Count all sequences of characters
我有一个字符数组'A'和'B'
什么是计算“跑步次数”的明智方法
例如:
AABBBAAAABBAB
应为6,因为有6次运行,如下所示。
1 2 3 4 5 6
AA BBB AAAA BB A B
尝试过类似的东西:
if (!(sortedRuns.get(i) == sortedRuns.get(i+1))) {
runsAmount++;
}
但显然遇到了“界外问题”
问题
e.g char array A A B B C C
array positions 0 1 2 3 4 5
当您到达位置5时, sortedRuns.get(i+1)
表示5+1=6
,该值不存在,因此例外
解
1.)遍历数组
2.)如果char更改,则递增运行,并将新的char分配给temp
char
String s="AABBBAAAABBAB";
int run=1;
// fetch first char
char temp=s.charAt(0);
// traverse char array
for (char ch : s.toCharArray()) {
// assign value of new char to temp and increment run
// when value of char changes
if (ch!=temp) {
run++;
temp=ch;
}
}
System.out.println(run);
输出:
6
我将使用辅助变量来保存最后一个字符。 当一个新字符不同于我的辅助变量时增加,然后更新此变量。 简单而不是超出范围的异常。
您可以使用正则表达式。 /(.)\\1*/给出6个匹配项。
(。)匹配任何字符。 然后\\ 1 *匹配尽可能多的第一个字符。
Java示例:
final String regex = "(.)\\1*";
final String string = "AABBBAAAABBAB";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) {
count ++;
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
System.out.println("Match count: " + count);
这具有使用任何字符串的优势。
您可以尝试以下简单的方法:
public static void main(String[] args) {
String s="AABBBAAAABBAB";
int charCount = s.length() - s.replaceAll("A", "").length();
System.out.println(charCount);
System.out.println(s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.