计算所有字符序列

时间:2017-01-06 11:19:19

标签: java arraylist

我有一个角色阵列' 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++;
}

但显然遇到了超出限制的问题'

4 个答案:

答案 0 :(得分:4)

问题

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 :(得分:0)

我会使用辅助变量来保存最后一个字符。然后在新字符与我的辅助变量不同时递增,然后更新此变量。容易而不是超出范围的例外。

答案 2 :(得分:0)

您可以使用正则表达式。 /(.)\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);

这具有使用任何字符串的优点。

答案 3 :(得分:0)

你可以试试这个简单的单行:

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);
}