由于String [暂停]超时而终止

loading...


-2

我想从用户和长号中获取一个字符串,它显示我们想要重复此字符串的次数,并找出它有多少字符'a' . 我使用了Array列表,但是当String的长度减少时,我收到一个超时错误 .

for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == 'a')
            count++;
    }
    if (s.length() > 1 && count!=0) {
        ArrayList<Character> list = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            list.add(s.charAt(i));
        }
        int head = 0;
        for (int i = list.size(); i < n; i++) {
            if (head == s.length()) {
                head = 0;
                list.add(s.charAt(head));
                head++;
            } else {
                list.add(s.charAt(head));
                head++;
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == 'a') {
                result++;
            }

        }

String s = scanner.nextLine();
long n = scanner.nextLong();
long result = repeatedString(s, n);

loading...

1回答

  • 0

    您可以通过一种非常简单的方式完成此操作:

    Scanner scanner = new Scanner(System.in);
    String s = scanner.nextLine(); // read string
    Long n = scanner.nextLong(); // read how many repetitions   
    Long count = (s.length() - s.replace("a", "").length()) * (n / s.length()); // repeation in one string * n / s.length()
    String remainingString = s.substring(0, (int) (n % s.length()));  
    count += remainingString.length() - remainingString.replace("a", "").length();
    System.out.println("'a' is repeated " + count + " times.");
    
评论

暂时没有评论!