为什么以下java代码不起作用?此代码中途停止并显示运行时错误

时间:2017-07-29 06:05:55

标签: java algorithm

给定一个字符串S和两个整数L,P,找到在字符串S中出现P次的长度为L的子字符串。例如,如果S = pujanshahpujan,N = 5,P = 2,我们需要子字符串在S中出现两次的长度为5.显然这是pujan。

    /* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
                Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();
        int t = sc.nextInt();

        while((t--)>0) {

            int l = sc.nextInt();
            int p = sc.nextInt();
            int a = l;
            String str1 = str;

            String temp;

            for(int i=0;i<str.length();i++) {
                temp = str.substring(i, a);
                a=a+1;
                int index = str.indexOf(temp);
                int count = 0;
                while (index != -1) {
                    count++;
                    str1 = str1.substring(index + 1);
                    index = str1.indexOf(temp);
                }
                if(count==p) {
                    System.out.println(temp);
                    a=i+l+1;
                    str1=str;
                }
                }
        }
    }
}

输入: mynameispujanshahandmybrothersnameischintanshah 1 4 2 输出: 名称 阿妹 我是 ANSH NSHA 沙

0 个答案:

没有答案