如何查找用户提供的字符串计数的所有连续字母?

时间:2017-08-22 18:59:29

标签: java arrays

我正在尝试用Java编写代码,该代码将查找用户提供的字符串中的所有连续字母,并提供其计数。

例如: 用户提供了字符串:“aaastt rr”。

我期待结果如下:

a - 3

t - 2

r - 2

我根据我的理解编写了以下代码,但没有按预期得到结果。

import java.util.Scanner;
public class ConsecutiveCharacters {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter string: ");
    char s[] = sc.nextLine().toCharArray();
    int count = 1;
    for(int i =0;i<s.length-1;i++){
        if(s[i]==s[i+1]){
            count++;
            System.out.println(s[i] + "-" + count);

        }
    }

}
}

我收到了结果:

A-2

A-3

T-4

R-5

这不是我所期待的。

请看一下,让我知道我失踪的地方。

非常感谢提前。

1 个答案:

答案 0 :(得分:3)

当您在阵列中遇到新角色时,您永远不会重置计数器。

随时使用起始字符和增量,并在找到新字符时更改字符,仅打印前一个字符并计算计数是否大于1.请注意最后一个字符连续的边缘情况

Scanner sc = new Scanner(System.in);
System.out.println("Enter string: ");
char s[] = sc.nextLine().toCharArray();
HashMap<Character, Integer> charsFound = new HashMap<>();
int count = 1;
char c = s[0];
for(int i = 1;i < s.length; i++)
{
    //check the edge case where the last of the array is consecutive chars
    if(c==s[i] && count >= 1 && s.length - 1 == i)
    {
        if(!charsFound.containsKey(c))
            charsFound.put(c, ++count);
        else if(charsFound.get(c) < ++count)
            charsFound.put(c, count);
    }
    //increment the count if the character is the same one
    else if(c==s[i])
    {
        count++;
    }
    //consecutive chain is broken, reset the count and our current character
    else
    {
        if(count > 1)
        {
            if(!charsFound.containsKey(c))
                charsFound.put(c, count);
            else if(charsFound.get(c) < count)
                charsFound.put(c, count);
        }
        //reset your variables for a new character
        c = s[i];
        count = 1;
    }
}

for (char knownCharacters : charsFound.keySet())
    if (charsFound.get(knownCharacters) > 1)
        System.out.println(knownCharacters + "-" + charsFound.get(knownCharacters));

输出

Enter string:
aabbbt s.r r rr
a-2
b-3
r-2

Enter string: 
aaastt rr
a-3
t-2
r-2

Enter string: 
aayy t t t.t ty ll fffff
a-2
y-2
l-2
f-5

Enter string: 
aa b aa c aaaaa
a-5