We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Traverse the string just 1 time. Save the weights of every possible uniform substring in a HashSet.
importjava.util.Scanner;importjava.util.HashSet;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscan=newScanner(System.in);Stringstr=scan.next();intn=scan.nextInt();HashSet<Integer>weights=getWeights(str);while(n-->0){intx=scan.nextInt();System.out.println(weights.contains(x)?"Yes":"No");}scan.close();}privatestaticHashSet<Integer>getWeights(Stringstr){HashSet<Integer>weights=newHashSet<>();intweight=0;charprev=' ';// so it doesn't match 1st characterfor(inti=0;i<str.length();i++){charcurr=str.charAt(i);if(curr!=prev){weight=0;}weight+=curr-'a'+1;weights.add(weight);prev=curr;}returnweights;}}
Weighted Uniform Strings
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
Time complexity: O(n)
Space complexity: O(n)
Traverse the string just 1 time. Save the weights of every possible uniform substring in a HashSet.
Let me know if you have any questions.