Weighted Uniform Strings

  • + 0 comments

    Java O(n + m)

    public static List<String> weightedUniformStrings(String s, List<Integer> queries) {
            List<String> result = new ArrayList<>();
            Set<Integer> weights = new HashSet<>();
            int count = 1;
            char prev = s.charAt(0);
            weights.add(prev - 'a' + 1);
    
            for (int i = 1; i < s.length(); i++) {
                char curr = s.charAt(i);
                if (curr == prev) {
                    count++;
                } else {
                    count = 1;
                    prev = curr;
                }
                weights.add((curr - 'a' + 1) * count);
            }
    
            for (int query : queries) {
                result.add(weights.contains(query) ? "Yes" : "No");
            }
    
            return result;
        }