Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
Alice has to go to work from his home. He finds it somehow the first day and keeps a note of it . In the office she finds the path to be longer and shortens it.

Given a string of the long path, shorten it. The result must be sorted lexicographically .

Example : SSNE to be simplified as ES

S stands for South, N for North, W for west , E for east.

What I have tried:

I'am thinking to delete all the same characters which occur together and keep only one of them.

eg:
SSSNNEW -> SNEW -> ENSW(Answer)

and later sort the string lexographically. Is it the right way ??
Posted
Updated 29-Jul-20 0:01am

No. Look at the example:
SSNE -> ES
What you need to do is remove opposites: A North and a South pair, and East and West pair. When you have removed pairs, you can sort.
 
Share this answer
 
Comments
CPallini 5-Nov-17 5:59am    
5.
Quote:
I'am thinking to delete all the same characters which occur together and keep only one of them.

Wrong
the principle is that N and S are opposite directions, same for E and W.
It means that if you have both; a move S will cancel a move N, same with E and W.
So SSSNNEW -> SSNEW -> SEW -> S
 
Share this answer
 
we can solve this problem using a stack if stack is empty push to the stack

always compare stack top with the current element in the string.

if top is S and element is S then push S. Similarly for N, E and W.

if top is S and element is N or vice versa then pop from stack and don't push.
if top is W and element is E or vice versa then pop from stack and don't push.

then pop all elements which are remaining in the stack and store that in a string ans sort the string and print the string.
 
Share this answer
 
Comments
CPallini 29-Jul-20 7:28am    
You are a bit late to the party, aren't you?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900