首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从用户提供的字符串中找到所有计数连续的字母?

如何从用户提供的字符串中找到所有计数连续的字母?
EN

Stack Overflow用户
提问于 2017-08-23 02:59:29
回答 1查看 2.2K关注 0票数 0

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

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

我期待的结果如下:

A-3

T-2

R-2

根据我的理解,我已经写了下面的代码,但没有得到预期的结果。

代码语言:javascript
复制
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

这不是我想要的。

请看一看,让我知道我遗漏了哪里。

在此之前,非常感谢您。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-23 03:17:44

当你在数组中遇到一个新字符时,你永远不会重置计数器。

使用开始字符和增量,并在每次发现新字符时更改字符,如果计数大于1,则仅打印前一个字符和计数。请注意最后一个字符连续的边缘大小写。

代码语言:javascript
复制
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));

输出

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45825069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档