• + 0 comments

    My solution in Java15.

    public static long repeatedString(String s, long n) {
        // Write your code here
            /*
                A easy approach to be seen is:
                - Seperate problem into the number of 'a' in full string and in substring
                + Count 'a' in full string and multiply it with a number of duplication.
                + Count 'a' in substring which has (n % l) letters with l = s.length()
                
                Solution:
                1. Calculate 'a' in substring, add it to variable "total"
                2. Calculate 'a' in full string, then multiply with the number of duplication and add to "total"
            */
            long count = 0, total = 0;
            int k = (int)(n % s.length());
            for(int i = 0; i < k; i++){
                if(s.charAt(i) == 'a') count++;
            }
            
            total += count; //number of 'a' in the substring
            for(int i = k; i < s.length(); i++){
                if(s.charAt(i) == 'a') count++;
            }
            
            //count now is the number of 'a' in the full string
            long duplication = n / s.length();
            total += count * duplication;
            
            return total;
        }