반복 문자열 코드 문제 해결

Lilah는 소문자 알파벳 s가 있는데, 그녀는 무한히 반복할 것이다.
"n"의 정수를 지정하여 Lilah 무한 문자열의 첫 번째 문자에서 "a"의 숫자를 찾아 인쇄합니다.
예를 들어 만약 문자열 s='abcac'와 n=10이 있다면 우리가 고려한 하위 문자열은 abcacacac이고 이것은 무한 문자열의 10개 문자이다.하위 문자열에 "a"가 네 번 나타납니다.
기능 설명
다음 편집기에서 repeatedString 함수를 완성합니다.무한 반복 문자열의 길이 접두사에 'a' 가 나타나는 횟수를 나타내는 정수를 되돌려야 합니다.
repeatedString에는 다음과 같은 매개변수가 있습니다.
4
  • s: 반복할 문자열.
    4
  • n: 고려할 문자 수입니다.
    입력 형식
    첫 번째 줄은 문자열 s를 포함하고, 두 번째 줄은 정수 n을 포함합니다.
    출력 형식
    무한히 여러 번 반복해서 만든 무한 문자열의 첫 번째 알파벳 a의 수량을 표시하는 정수를 인쇄합니다.
    샘플 입력
    아바
    10
    샘플 출력
    7
    해석하다
    무한 문자열의 첫 번째 자모는 "abaa"입니다.a가 있기 때문에, 우리는 새 줄에 인쇄합니다.

    솔루션
    
    
    function repeatedString($s, $n) {
        // check the number of occurrences of letter 'a' on given string $s
        $a_occurrences_in_s = substr_count($s, 'a');
    
        // check how many occurrences of string $s belongs to an repeated string $s of length of $n
        $s_occurrences_qty = floor($n / strlen($s));
    
        // get the $s occurrences left
        $s_occurrences_left = $n - ($s_occurrences_qty * strlen($s));
    
        // left string
        $s_left = substr($s, 0, $s_occurrences_left);
    
        // 'a' occurrences in left string
        $a_occurrences_in_s_left = substr_count($s_left, 'a');
    
        // occurrencies of 'a' on the entire repeated string of $s with a length of $n
        return ($a_occurrences_in_s * $s_occurrences_qty) + $a_occurrences_in_s_left;
    }
    
  • 좋은 웹페이지 즐겨찾기