text: Total time required to travel a path denoted by a given string | Java program for above approach ; Function to calculate time taken to travel the path ; Stores total time ; Initial position ; Stores visited segments ; Check whether segment is present in the set ; Increment the value of time by 2 ; Insert segment into the set ; Print the value of time ; Driver Code
code: import java . util . * ; class GFG { static void calcTotalTime ( String path ) { int time = 0 ; int x = 0 , y = 0 ; Set < String > s = new HashSet < > ( ) ; for ( int i = 0 ; i < path . length ( ) ; i ++ ) { int p = x ; int q = y ; if ( path . charAt ( i ) == ' N ' ) y ++ ; else if ( path . charAt ( i ) == ' S ' ) y -- ; else if ( path . charAt ( i ) == ' E ' ) x ++ ; else if ( path . charAt ( i ) == ' W ' ) x -- ; String o = ( p + x ) + " ▁ " + ( q + y ) ; if ( ! s . contains ( o ) ) { time += 2 ; s . add ( o ) ; } else time += 1 ; } System . out . println ( time ) ; } public static void main ( String [ ] args ) { String path = " NSE " ; calcTotalTime ( path ) ; } }