Shortest direction (GFG)
A person wants to go from origin to a particular location, he can move in only 4 directions(i.e East, West, North, South) but his friend gave him a long route, help a person to find minimum Moves so that he can reach to the destination.
Note: You need to print the lexicographically sorted string. Assume the string will have only ‘E’ ‘N’ ‘S’ ‘W’ characters.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is S, S is the long route(string).
Output:
Print minimum Moves so that he can reach to the destination.
Constraints:
1 ≤ T ≤ 100
1 ≤ |length of S| ≤ 1000
Example:
Input
2
SSSNEEEW
NESNWES
Output
EESS
E
SOLUTION:
t=int(input())
for i in range (t):
p=input()
s=0
e=0
n=0
w=0
for i in p:
if i =="S":
s +=1
elif i=="W":
w +=1
elif i =="E":
e +=1
elif i == "N":
n +=1
if e>w:
print("E"*(e-w),end=" ")
if w>e:
print("W"*(w-e),end=" ")
if n>s:
print("N"*(n-s),end=" ")
if s>n:
print("S"*(s-n),end=" ")
print()
Comments
Post a Comment