Delete consecutive same words in a sequence

QUESTION

Given a sequence of n strings, the task is to check if any two similar words come together then they destroy each other then print the number of words left in the sequence after this pairwise destruction.

“TESTCASE_1”: “tom jerry jerry tom\n###—###SEPERATOR—###—\n0”, “TESTCASE_2”: “ab aa aa bcd ab\n###—###SEPERATOR—###—\n3”, “TESTCASE_3”: “ab ba cd cd gf\n###—###SEPERATOR—###—\n3”, “TESTCASE_4”: “xy xy cd de cd ef\n###—###SEPERATOR—###—\n4”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

import java.io.*;
import java.util.*;

class TestClass
{
	// Method to find the size of manipulated sequence
	static int removeConsecutiveSame(Vector <String > v)
	{
	    int n = v.size();
	 
	    // Start traversing the sequence
	    for (int i=0; i<n-1; )
	    {
	        // Compare the current string with next one
	        // Erase both if equal
	        if (v.get(i).equals(v.get(i+1)))
	        {
	            // Erase function delete the element and
	            // also shifts other element that's why
	            // i is not updated
	        	v.remove(i);
	        	v.remove(i);
	 
	            // Update i, as to check from previous
	            // element again
	            if (i > 0)
	                i--;
	 
	            // Reduce sequence size
	            n = n-2;
	        }
	 
	        // Increment i, if not equal
	        else
	            i++;
	    }
	 
	    // Return modified size
	    return v.size();
	}
	
    // Driver method
    public static void main(String[] args) 
    {
    	Vector<String> v = new Vector<>();
      Scanner sc=new Scanner(System.in);
      String s=sc.nextLine();
      String []str=s.split(" ");
      for(int i=str.length-1;i>=0;i--)

    	v.addElement(str[i]);

        System.out.println(removeConsecutiveSame(v));
    }
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro