Next lexicographical string - PrismoSkills
Problem: Write code to print the lexicographical next string for a given string.
(As in dictionary, next word after this word but having similar letters) For ex:
i/p abcd
o/p abdc
i/p abcged
o/p abdceg
Solution:
Find the number of characters at the end of string that are sorted
decreasingly e.g. in "abcgda" the length of such sub-string is 3 ( "gda" ).
Then look at the char before this sub-string (here it is 'c' ).
This character must be replaced with the smallest character in
the decreasing sub-sequence which is bigger than this char (here it's 'd').
Then sort the decreasing sub-string to be increasing
So the next lexicographical string of "abcgda" is "abdacg" ('d' is replaced
with 'c' and then "gca" is sorted to be "acg")
Note If a string is sorted decreasingly like "dcba" it's next char does
not exist so it's next string doesn't exist
Read full article from Next lexicographical string - PrismoSkills
No comments:
Post a Comment