Thursday, October 13, 2016

Reverse an array without affecting special characters

Input:   str = "a,b$c"
Output:  str = "c,b$a"
Note that $ and , are not moved anywhere. 
Only subsequence "abc" is reversed

Input:   str = "Ab,c,de!$"
Output:  str = "ed,c,bA!$"

Input string: a!!!b.c.d,e'f,ghi
Output string: i!!!h.g.f,e'd,cba

Here is the algorithm
1) Let input string be 'str[]' and length of string be 'n'
2) l = 0, r = n-1
3) While l is smaller than r, do following
    a) If str[l] is not an alphabetic character, do l++
    b) Else If str[r] is not an alphabetic character, do r--
    c) Else (both left and right are alphabetic) swap str[l] and str[r]

Here is javascript impelementation:


No comments:

Post a Comment