gpt4 book ai didi

java - hackerrank 中的重复字符串问题获取时间限制问题

转载 作者:行者123 更新时间:2023-12-01 18:45:02 24 4
gpt4 key购买 nike

我正在解决重复字符串 hackerrank 问题。但是所有的测试用例都没有运行可能是我的逻辑不正确。问题是这样的

repeated string problem

下面给出了我的代码,其中包含没有变量的repeatedString和countingA函数i、a 和无穷大字符串...

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the repeatedString function below.
static long repeatedString(String s, long n) {
long i=1;
String infinityString="";
while(s.length()*i<=n)
{
infinityString+=s;
i++;
}
if(s.length()%infinityString.length()==0){
return countingA(infinityString);
}else{
infinityString+=s.substring(0,(s.length()%infinityString.length())-1);
return countingA(infinityString);
}
}
public static long countingA(String infinity)
{
long a=0;
for(int i=0;i<infinity.length();i++)
{
if(infinity.charAt(i)=='a')
{
a++;
}
}
return a;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

String s = scanner.nextLine();

long n = scanner.nextLong();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

long result = repeatedString(s, n);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();

scanner.close();
}
}

最佳答案

也许可以试试这个,

static long countA(String s, long n) {
long totalCount = 0;
long aCount = 0;
long times = n / s.length();

for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == 'a')
aCount++;
}
totalCount = times * aCount;
aCount = 0;
if(n%s.length() != 0) {
for(int i=0;i<n - (times * s.length());i++)
aCount++;
}
return totalCount + aCount;
}

关于java - hackerrank 中的重复字符串问题获取时间限制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59854635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com