简体   繁体   English

将一个字符串转换为另一字符串

[英]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. 有一个字符串,其字符只能是ab_ ,字符串中只有一个_

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 . _可以与其相邻字符交换,例如a_ba可以更改为_abaab_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 ). (例如aba_ab可以转换为a_ababababa_ ,但是ab_aab不能转换为abaa_b ,因为a不能跳过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. 您的代码基本上是在此图中实现DFS ,但DFS并非最佳。 You should try implementing a BFS , which is guaranteed to be optimal (always finds the shortest path). 您应该尝试实现BFS ,这可以保证是最佳的(总是找到最短的路径)。

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. 更为复杂的优化(以缩短运行时间)包括A *搜索算法和双向搜索,但是您现在应该避免使用这些算法,而应专注于更简单的BFS,恕我直言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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