Super Reduced String Hackerrank Solution In Java.

Super Reduced String Hackerrank Solution In Java.

Super Reduced String Hackerrank Solution In Java



Hello Programmers,

Today we will solve an easy hackerrank problem which is Super Reduced String with java.



Question:


Steve has a string of lowercase characters in a range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation, he selects a pair of adjacent lowercase letters that match, and he deletes them. For instance, the string 'aab' could be shortened to 'b' in one operation.

Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print Empty String.


Function Description

Complete the superReducedString function in the editor below. It should return the super-reduced string or Empty String if the final string is empty.

superReducedString has the following parameter(s):

  • s: a string to reduce

Input Format

A single string, s.

Constraints

Output Format

If the final string is empty, print Empty String; otherwise, print the final non-reducible string.


Solution:


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {

    // Complete the superReducedString function below.
    static String superReducedString(String s) {

           StringBuilder sb=new StringBuilder(s);
          for(int i=1;i<sb.length();i++)
{ if(sb.charAt(i)==sb.charAt(i-1)) { sb.delete(i-1,i+1); i=0; } }

           if(sb.length()==0)
           {
               return ("Empty String");
           }
           else
           {
           return (sb.toString());
           }

    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s = bufferedReader.readLine();

        String result = superReducedString(s);

        bufferedWriter.write(result);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}


Others Usefull Post:



Sharing Is Caring...

Comments :

Post a Comment