A weighted string is a string of lowercase English letters where each letter has a weight
The weight of a string is the sum of the weights of its characters.
1.A uniform string consists of a single character repeated zero or more times. For example, ccc
and a
are uniform strings, but bcb
and cd
are not.
Given a string,s, let U be the set of weights for all possible uniform contiguous substrings of a string s. There will be n queries to answer where each query consists of a single integer. Create a return array where for each query, the value is Yes if. Otherwise, append No
.
Example:
Input:
abccddde613125910
Output:
Yes Yes Yes Yes No No
Approach:
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;public class WeightedUniformStrings {public static void main(String[] args) {
String s = "abccddde";int[] queries = { 1, 3, 12, 5, 9, 10 };String[] result = weightedUniformStrings(s, queries);System.out.println(Arrays.toString(result));}private static String[] weightedUniformStrings(String s, int[] queries) {List<String> res = new ArrayList<String>();HashSet<Integer> weights = getWeights(s);for (int integer : queries) {String str = weights.contains(integer) ? "Yes" : "No";res.add(str);}return res.toArray(new String[0]);}private static HashSet<Integer> getWeights(String str) {HashSet<Integer> weights = new HashSet<>();int weight = 0;char prev = ' ';for (int i = 0; i < str.length(); i++) {char curr = str.charAt(i);if (curr != prev) {weight = 0;}weight += curr - 'a' + 1;weights.add(weight);prev = curr;}return weights;}}
C++
#include <bits/stdc++.h>using namespace std;vector<string> weightedUniformStrings(string s, vector<int> queries){vector<string> res;set<int> st;st.insert(s[0] - 'a' + 1);for (int i = 1; i < s.size(); i++){if (s[i] == s[i - 1]){int k = 2;while (s[i] == s[i - 1]){int x = s[i] - 'a' + 1;st.insert(k * x);i++;k++;}st.insert(s[i] - 'a' + 1);}elsest.insert(s[i] - 'a' + 1);}for (int i = 0; i < queries.size(); i++){if (st.find(queries[i]) != st.end())res.push_back("Yes");elseres.push_back("No");}return res;}int main(){string s = "abccddde";int queries_count = 6;vector<int> queries = {1, 3, 12, 5, 9, 10};vector<string> result = weightedUniformStrings(s, queries);for (int i = 0; i < result.size(); i++){cout << result[i];if (i != result.size() - 1){cout << "\n";}}cout << "\n";return 0;}
No comments:
Post a Comment