Decrypt a string according to given rules | Java program to decrypt the original string ; Function to return the original string after decryption ; Stores the decrypted string ; If length is odd ; Step counter ; Starting and ending index ; Iterate till all characters are decrypted ; Even step ; Odd step ; If length is even ; Step counter ; Starting and ending index ; Even step ; Odd step ; Reverse the decrypted string ; Driver code
import java . io . * ; import java . util . * ; class GFG { public static String decrypt ( String s , int l ) { String ans = " " ; if ( l % 2 == 1 ) { int cnt = 0 ; int indl = 0 , indr = l - 1 ; while ( ans . length ( ) != l ) { if ( cnt % 2 == 0 ) ans += s . charAt ( indl ++ ) ; else ans += s . charAt ( indr -- ) ; cnt ++ ; } } else { int cnt = 0 ; int indl = 0 , indr = l - 1 ; while ( ans . length ( ) != l ) { if ( cnt % 2 == 0 ) ans += s . charAt ( indr -- ) ; else ans += s . charAt ( indl ++ ) ; cnt ++ ; } } StringBuffer sbr = new StringBuffer ( ans ) ; sbr . reverse ( ) ; return sbr . toString ( ) ; } public static void main ( String [ ] args ) { String s = " segosegekfrek " ; int l = s . length ( ) ; System . out . println ( decrypt ( s , l ) ) ; } }