Weighted Uniform Strings

  • + 0 comments

    Java solution using stack

    public static List<String> weightedUniformStrings(String s, List<Integer> queries) {
        // Write your code here
            HashSet<Integer> set = new HashSet<>();
            Stack<Character> stack = new Stack<>();
            List<String> result = new ArrayList<>();
            int weight = 0;
            for (char c : s.toCharArray()) {
                if (!stack.isEmpty() && stack.peek() != c) {
                    weight = 0;
                    while (!stack.isEmpty())
                        stack.pop();
                }
                stack.push(c);
                weight += c - 'a' + 1;
                set.add(weight);
    
            }
            for (int q : queries) {
                if (set.contains(q))
                    result.add("Yes");
                else
                    result.add("No");
            }
            return result;
        }
    
    }