Weighted Uniform Strings

  • + 0 comments

    Java Solution using a Set O(n+q); n is the length of the string and q is the length of the queries list

    public static List<String> weightedUniformStrings(String s, List<Integer> queries) {
            Set<Integer> sWeights = new HashSet<>();
            char currChar = '0';
            int subWeight = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (currChar!=s.charAt(i)) {
                    currChar = s.charAt(i);
                    subWeight = 0;
                }
                subWeight+=(s.charAt(i)-'a'+1);
                sWeights.add(subWeight);
            }
            
            List<String> res = new ArrayList<>();
            for (int q : queries) {
                if (sWeights.contains(q))
                    res.add("Yes");
                else 
                    res.add("No");
            }
            
            return res;
        }