计数和所有字符相同的最大字符串的起始索引

时间:2013-06-06 12:08:11

标签: java java-ee

在给定的字符串中,我想找出最大子字符串的起始索引,它们全部由相同的字符组成,并且还计算主字符串中出现子字符串的次数。

ex:“aaakkkkbbkkkkk” 在这种情况下,子串“kkkkk”的计数为5,起始位置为9。

到目前为止我的代码:

String str = "aaakkkkbbkkkkk";
int count = 0;
//converting string into character array
char[] vals = str.toCharArray(); 

for(int i=0; i < vals.length; ){

   for(int j=i+1; j<vals.length; j++){
       //if value match then increment counter
       if(vals[i]== str.charAt(j)){
           counter++;
       }
       //else break from inner loop 
       break; //break from inner loop
   }
   //assign the index value of j to the i to start with new substring
   i = vals.indexOf(j);
}

我的问题:无法存储计数器值,因为此计数器值是子字符串的实际出现次数,稍后我会将子字符串与计数器出现进行比较。

我也不符合我的逻辑。

4 个答案:

答案 0 :(得分:2)

1.使用单独的变量来存储第一次出现的子串

2.制作将存储最后序列长度的其他计数器

3.新序列启动时重置计数器

String str = "aaakkkkbbkkkkk";
int count = 0;
int firstOccurence = 0;
int prevSequenceLength = 0;
//converting string into character array
char[] vals = str.toCharArray(); 

for(int i=0; i < vals.length; ){

   for(int j=i+1; j<vals.length; j++){
       //if value match then increment counter
       if(vals[i]== str.charAt(j)){
           counter++;
       }
       else
      {
       //set the prevSequenceLength to counter value if it is less than counter value
       if(prevSequenceLength<counter)
        {
          prevSequenceLength=counter;
         //make firstOccurence to  j - counter
         firstOccurence = j-counter;
       }

       //first reset the counter to 0;
       counter = 0;

       //else break from inner loop 
       break; //break from inner loop
   }
   //assign the index value of j to the i to start with new substring
   i = vals.indexOf(j);
}

答案 1 :(得分:2)

还有一个解决方案:

class Sample {
    static int max = 0, maxStartPos = -1;

    public static void main(String[] args) {
        search("aaakkkkbbkkkkk".toCharArray());
        System.out.println(String.format("max len: %d, start pos: %d", max, maxStartPos));

        search("xxxxxh".toCharArray());
        System.out.println(String.format("max len: %d, start pos: %d", max, maxStartPos));

        search("hxxxxxhyyyyyyh".toCharArray());
        System.out.println(String.format("max len: %d, start pos: %d", max, maxStartPos));
    }

    private static void search(char[] chars) {
        max = 0; maxStartPos = 0;

        int len = 0, startPos = 0;
        char start = chars[0];
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == start) {
                len++;
            } else {
                if (len > max) {
                    updateMaxResults(len, startPos);
                }
                startPos = i;
                len = 1;
                start = chars[i];
            }
        }
        if (len > max) {
            updateMaxResults(len, startPos);
        }
    }

    private static void updateMaxResults(int len, int startPos) {
        max = len;
        maxStartPos = startPos;
    }
}

答案 2 :(得分:2)

我认为这对你有帮助, 我知道它很小,很容易看到每一个,...

    public static void main(String[] args) {


        String str = "aaakkkkkkkbbkkkkk";

        char[] var = str.toCharArray();

        for(int i=0; i<var.length;i++)
            System.out.print(" "+var[i]);


        int final_index=0; // this is for final index what we want

        int max_size=0; // for maximum no. of time the same char repeats continiously..
        int size=0; // this for finding size of sub string..
        char pre_char=var[0]; // pre_char is used check with present char in the array where the i position is shifted..



        // here is the loop..
        // we don't need much loops to this
        // while we are reading , the comparison is also done parallely.. 
        for(int i=1;i<var.length;i++) // here i starts from 1 because 0th char is shfted into pre_char 
            //and now comparion is starts from next char ie from 1th position
        {
//          System.out.println("i=="+i+" size "+size+"  prechar== "+pre_char+ "  var[i] ="+var[i]+" max size=="+max_size);
//          System.out.println("..........................");
            if(pre_char==var[i]) // here condition is checking. if its same with previous char, its means same char is occur again..
            {
                size+=1;
            }else{ // else means the sub string is has different char 
                if(max_size<size) // now check for whether any maximum size is occured priviously or not..
                {
                    max_size=size;
                    final_index=i-size;
                }
                size=0;
            }
            pre_char=var[i];
        }

        // now this for final 
        // its means if the max sub string is at the ending position, the above for loop breaks at the last element 
        // in this case we check if the last sub string is max or not..

        if(max_size<size)
        {
            max_size=size;
            final_index=var.length-size;
        }
        // then this is the final what we wana,,,,, 
        System.out.print("Max size is "+(max_size+1)+"  index is "+final_index);



    }

快乐编码.. @ All .....

答案 3 :(得分:0)

此解决方案仅找到一个可能的子字符串,可能有几个具有相同最大重复字符数的子字符串。所以这是我的解决方案,它将返回一个列表。

代码如下:

import java.util.List; 导入java.util.ArrayList;

公共类SubString {

public static void main(String[] args) {

    String a1 = "12311m22n33";

    char[] arrays = (a1+"\n").toCharArray();


    //value is char +"_" +  start
    List<String[]> lists = new ArrayList<>();

    int len = 0;
    int start = -1;
    char prev = '\n';
    int position= -1;
    int maxLen = 0;
    for (char a: arrays) {
        position++;
        if (a != prev) {
            if (len > maxLen ) {
                lists.clear();  
                String[] sq = {prev+"", start+""};
                lists.add(sq);
                maxLen = len;

            } else if ( len == maxLen && len != 0) {
                String[] sq = {prev+"", start+""};
                lists.add(sq);
            }

            prev = a;
            len = 1;
            start = position;

        } else {
            len++;
        }
    }


    for(String[] a: lists) {

        String s = a[0];
        String st = a[1];
        System.out.println("The longest length: " + maxLen + " is char: " + s + " start at : " + st);
    }

}

}

//此示例字符串的输出为: 最长长度:2是字符:1开始于:3 最长的长度:2是字符:2开始于:6 最长的长度:2是字符:3始于:9