Amanda has a string of lowercase letters that she wants to copy to a new string. She can perform the following operations with the given costs. She can perform them any number of times to construct a new string p:
1.Append a character to the end of the string p at a cost of the dollar.
2.Choose any substring of p and append it to the end of p at no charge.
Given n strings s[i], find and print the minimum cost of copying each s[i] to p[i] on a new line.
1.Append a character to the end of the string p at a cost of the dollar.
2.Choose any substring of p and append it to the end of p at no charge.
Given n strings s[i], find and print the minimum cost of copying each s[i] to p[i] on a new line.
Example:
Input: q=1, s="abab"
Output: 2
Approach
Java
import java.util.HashSet;public class StringConstruction {public static void main(String[] args) {String str = "abc";int count = stringConstruction(str);System.out.println(count);}static int stringConstruction(String s) {HashSet<Character> set = new HashSet<Character>();for (int i = 0; i < s.length(); i++) {set.add(s.charAt(i));}return set.size();}}
C++
#include <bits/stdc++.h>using namespace std;int stringConstruction(string s){int f[26] = {0}, cnt = 0;for (int i = 0; i < s.size(); i++){if (f[s[i] - 'a'] == 0){f[s[i] - 'a']++;cnt++;}elsef[s[i] - 'a']++;}return cnt;}int main(){int q = 1;string s = "abab";int result = stringConstruction(s);cout << result << "\n";return 0;}
No comments:
Post a Comment