There is a string, s, of lowercase English letters that is repeated infinitely many times. Given an integer, n, find and print the number of letter a's in the first n letters of the infinite string.
Example
s = 'abcac'
n = 10
The substring we consider is abcacabcac, the first 10 characters of the infinite string. There are 4 occurrences of a in the substring.
Function Description
Complete the repeatedString function in the editor below.
repeatedString has the following parameter(s):
- s: a string to repeat
- n: the number of characters to consider
Returns
- int: the frequency of a in the substring
import Foundation
/*
* Complete the 'repeatedString' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. STRING s
* 2. LONG_INTEGER n
*/
func repeatedString(s: String, n: Int) -> Int {
var q = n/(s.count)
var count = (s.components(separatedBy: "a").count - 1) * q
var r = n%(s.count)
let idx = s.index(s.startIndex, offsetBy: r)
count += s[s.startIndex..<idx].components(separatedBy: "a").count - 1
return count
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let s = readLine() else { fatalError("Bad input") }
guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
let result = repeatedString(s: s, n: n)
fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
// 테스트 케이스 - 제약 범위 (최대한 반복문 줄이기)
// for문 대신 각 계산 후, 간단한 수학식으로 변환
'Computer Science > Algorithm with Code' 카테고리의 다른 글
[HackerRank] Preparation_Kit (06. Left Rotation) [Array] (0) | 2024.09.21 |
---|---|
[HackerRank] Preparation_Kit (05. 2D Array - DS) [Array] (0) | 2024.09.19 |
[HackerRank] Preparation_Kit (03. Jumping on the Clouds) (0) | 2024.09.16 |
[HackerRank] Preparation_Kit (02. Counting Valleys) (2) | 2024.09.16 |
[HackerRank] Preparation_Kit (01. Sales by Match) (0) | 2024.09.14 |