HackerRank | Repeated String | Solution Explained (Java)

preview_player
Показать описание
Running Time: O(N)
Space Complexity: O(N)

Always be pluggin:
Рекомендации по теме
Комментарии
Автор

You have got a really great sense of humor.

kunal_chand
Автор

You have helped me soo much, i was banging my head against the wall i had a diferent approach but it wasnt succesfull on other test cases
Build this on PHP
$letter_count_a = substr_count($s, "a");
$char_length = strlen($s);
$total = (int)($n / $char_length);
$remainder = $n % $char_length;
$count = $letter_count_a * $total;
for($i = 0; $i < $remainder; $i++){
if($s[$i] == "a") {
$count++;
}
}
return $count;

PortiaNomsa
Автор

Nice! You can also make it simpler by instead of creating a char array just use "s.charAt(i)== 'a'" in the if() statement

MsSWAGboss
Автор

The explanation is not as gold l fluid to understand because you are thinking out loud, but it is good that it is written out.

codelinx
Автор

static long repeatedString(String s, long n) {
int strLength = s.length();
long q = 0, r = 0;
q = n / strLength;
r = n % strLength;
long partialStrLen = (r == 0) ? 0 : r;
long aCount = q * getLetterCount(s, s.length()) + getLetterCount(s, partialStrLen);
return aCount;
}

public static long getLetterCount(String s, long strLength) {
long count = 0;
for (int i = 0; i < strLength; i++) {
if (s.charAt(i) == 'a')
count++;
}
return count;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
long n = sc.nextLong();
long aCount = repeatedString(s, n);

sc.close();
}

tamalbarman
Автор

Um, excuse me mister, but can you please turn down the lights?

NarutoUzumakiNamika
Автор

very helpful, I took a different approach which wasn't as efficient.. Made a StringBuilder with a capacity limit or repeated the string n times then get a substring of 0, n then using .Count(p => p == 'a') method from c#...

losetelevision
Автор

Was doing this in JS, and instead of doing Math.floor, I was doing Math.round smh.

jammy