Friday, February 26, 2021

Published February 26, 2021 by Anonymous with 0 comment

Shortest string possible after removal of all pairs of similar adjacent characters

  

import java.io.*;

import java.lang.*;

import java.util.*;

  

class GFG {

  

    

    

    static String removeAdjacent(String s)

    {

        

        if (s.length() == 1)

            return s;

  

        

        StringBuilder sb = new StringBuilder("");

  

        

        for (int i = 0;

             i < s.length() - 1; i++) {

            char c = s.charAt(i);

            char d = s.charAt(i + 1);

  

            

            

            if (c != d) {

                sb.append(c);

  

                if (i == s.length() - 2) {

                    sb.append(d);

                }

            }

  

            

            

            else {

                for (int j = i + 2;

                     j < s.length(); j++)

  

                    

                    

                    sb.append(s.charAt(j));

  

                return sb.toString();

            }

        }

  

        

        return sb.toString();

    }

  

    

    

    

    public static void reduceString(String s)

    {

        

        String result = "";

  

        

        

        String pre = s;

  

        while (true) {

            

            

            

            result = removeAdjacent(pre);

  

            

            if (result.equals(pre))

                break;

  

            

            

            pre = result;

        }

  

        if (result.length() != 0)

            System.out.println(result);

  

        

        else

            System.out.println("Empty String");

    }

  

    

    public static void main(String[] args)

    {

        String S = "aaabccddd";

        reduceString(S);

    }

}

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment