简体   繁体   中英

Transform one string to another string

There is a string whose characters can only be either a , b or _ ,there is only one _ in the string.

At each step, we can modify the string as follows:

_ can be swapped with its adjacent character, example a_ba can be changed to either _aba or ab_a .

You can swap _ character with next to adjacent character only if adjacent character is different from next to adjacent character. (For example aba_ab can be converted into a_abab or ababa_ , but ab_aab cannot be converted to abaa_b , because a cannot jump over a ).

You are given two strings, the initial state and the final state (lengths will be same), you have to output the minimum number of steps required to change the string in initial state to the string in the final state.

example:

string s1 ,s2 ;
input: s1 = a_b , s2 = ab_
output: 1
input: s1 = aba_a , s2 = _baaa
output: 2

This can be solved when you think of the problem as a graph problem pretty simply.

The vertices are all the possible states, and there is an edge from two vertices, if you can get from one to the other using a single move.
The problem now, is finding shortest path from source to destination in this graph.

Your code is basically implementing a DFS on this graph, but DFS is not optimal. You should try implementing a BFS , which is guaranteed to be optimal (always finds the shortest path).

More complex optimizations (for faster running time) include A* search algorithm and bi-directional search, but you should avoid these for now and focus on the simpler BFS, IMHO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM