使用Java在字符串中查找最长的连续字符集

时间:2017-04-04 04:30:18

标签: java string count

我知道我错过了一条线,我相信它的sudo会是:因为i = 0到str.length - 1:

我把那条线放在我认为它应该去的地方,但我不确定我会怎么写呢?对此非常陌生,任何帮助表示赞赏!

public static void main (String[] args)
{
    c = new Console ();

    String size;

    c.print ("Enter a string: ");
    size = c.readString ();

    String answer = sizeOfLargestGroup (size);

    c.println (answer);
} // main method


private static String sizeOfLargestGroup (String size)

{
    maxCount = 1;
    currCount = 1;
    for i = 0 to str.length - 1:
    if (currCount > maxCount)
        maxCount = currCount;
    if (str [i] == str [i + 1])
        currCount++;
    else
        currCount = 1;
    return maxCount;

}

1 个答案:

答案 0 :(得分:0)

考虑我的以下答案,我在方法中声明2个int,一个知道多少个字母,一个知道哪个更大

 public static void main(String[] args)
            {
                Scanner scan = new Scanner(System.in);
                System.out.println("Please enter a string");
                String mySize=scan.nextLine();
                int answer=sizeOfLargestGroup(mySize);
                System.out.println(answer);
            }
            public static int sizeOfLargestGroup (String size)
            {
                int myCharInt=1;//get the character
                int myCurrent=0;//get the largest myCharInt
                for(int i=0;i<size.length()-1;++i)
                {

                    if(size.charAt(i)==size.charAt(i+1))
                        myCharInt++;

                    else
                        myCharInt=1;
                    if(myCurrent<myCharInt)//test the current value of myCharInt if it is largest switch it to the current value of myCurrent
                    myCurrent=myCharInt;

                }

                return myCurrent;


            }