본문 바로가기

Computer Science/Algorithm with Code

[HackerRank] Preparation_Kit (04. Repeated String)

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문 대신 각 계산 후, 간단한 수학식으로 변환


https://www.hackerrank.com/challenges/repeated-string/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup