Nice fast(ish) 115ms simple bruteforce Java complete with unit test (that's right)


  • 0
    P

    Code should be self-explanatory

    import org.junit.jupiter.api.Test;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    public class Solution {
    
        private int countS2inS1(final char[] s1, final char[] s2) {
            int count = 0;
            int s2Pointer = 0;
    
            for (final char c1 : s1) {
                if (c1 == s2[s2Pointer]) {
                    s2Pointer++;
    
                    if (s2Pointer == s2.length) {
                        s2Pointer = 0;
                        count++;
                    }
                }
            }
    
            return count;
        }
    
        public int getMaxRepetitions(final String s1, final int n1, final String s2, final int n2) {
            final Set<Character> s1Chars = new HashSet<>();
    
            for (final char c1 : s1.toCharArray()) {
                s1Chars.add(c1);
            }
    
            final Set<Character> s2Chars = new HashSet<>();
    
            for (final char c2 : s2.toCharArray()) {
                s2Chars.add(c2);
            }
    
            if (s1Chars.size() == 1 && s2Chars.size() == 1 && s1Chars.iterator().next() == s2Chars.iterator().next()) {
                return (s1.length() * n1) / (s2.length() * n2);
            }
    
            final StringBuilder sb1 = new StringBuilder();
    
            for (int i = 0; i < (n1 / n2); i++) {
                sb1.append(s1);
            }
    
            if (sb1.length() == 0) {
                sb1.append(s1);
                return Math.max(0, countS2inS1(sb1.toString().toCharArray(), s2.toCharArray()) - 1);
            }
    
            return countS2inS1(sb1.toString().toCharArray(), s2.toCharArray());
        }
    
        @Test
        public void test() {
            assertEquals(2, new Solution().getMaxRepetitions("acb", 4, "ab", 2));
            assertEquals(4, new Solution().getMaxRepetitions("aaa", 3, "aa", 1));
            assertEquals(7, new Solution().getMaxRepetitions("baba", 11, "baab", 1));
            assertEquals(1, new Solution().getMaxRepetitions("adasfdgdftadwfwfereredsfssas", 500, "fw", 555));
            assertEquals(100000000, new Solution().getMaxRepetitions("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1000000, "a", 1));
            assertEquals(200000, new Solution().getMaxRepetitions("aahumeaylnlfdxfircvscxggbwkfnqduxwfnfozvsrtkjprepggxrpnrvystmwcysyycqpevikeffmznimkkasvwsrenazkycxf", 1000000, "aac", 10));
            assertEquals(0, new Solution().getMaxRepetitions("musicforever", 10, "lovelive", 100000));
        }
    
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.