Header Ad

HackerRank String Construction problem solution

In this HackerRank String Construction problem solution, we have given n strings and we need to find and print the minimum cost of copying each string to a new string on a new line.

HackerRank String Construction problem solution


Problem solution in Python.

#!/bin/python3

import sys


n = int(input().strip())
for a0 in range(n):
    s = input().strip()
    p_set = set()
    for c in s:
        p_set.add(c)
    print(len(p_set))

{"mode":"full","isActive":false}


Problem solution in Java.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        
        for (int i = 0; i < n; i++)
        {
            int custo = 0;
            String s = input.next();
            StringBuilder p = new StringBuilder();
            for (int j = 0; j < s.length(); j++)
            {
                String c = String.valueOf(s.charAt(j));
                if (p.indexOf(c) == -1) ++custo;
                p = p.append(c);
            }
            System.out.println(custo);
        }
    }
}

{"mode":"full","isActive":false}


Problem solution in C++.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int main(){
    int n;
    cin >> n;
    for(int a0 = 0; a0 < n; a0++){
        string s, soFar = "";
        cin >> s;
        int cost = 0;
        for (char c : s) {
            if (soFar.find(c) == string::npos)
                cost++;
            soFar = soFar + c;
        }
        cout << cost << endl;
    }
    return 0;
}

{"mode":"full","isActive":false}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n,i,j,c=0; 
    scanf("%d",&n);
    for(int a0 = 0; a0 < n; a0++){
        char* s = (char *)malloc(10240 * sizeof(char));
        scanf("%s",s);
        for(i=0;i<strlen(s);i++){
            for(j=0;j<i;j++){
                if(s[i]==s[j])break;
            }if(i==j){c++;}
        }
       printf("%d\n",c);c=0; 
        
        
    }
    return 0;
}

{"mode":"full","isActive":false}


Post a Comment

0 Comments