Given an array of equal-length strings, you’d like to know if it’s possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. Return true if it’s possible, and false if not.
Note: You’re only rearranging the order of the strings, not the order of the letters within the strings!
Example
inputArray = ["aba", "bbb", "bab"]
, the output should besolution(inputArray) = false.
There are 6 possible arrangements for these strings:
["aba", "bbb", "bab"]
["aba", "bab", "bbb"]
["bbb", "aba", "bab"]
["bbb", "bab", "aba"]
["bab", "bbb", "aba"]
["bab", "aba", "bbb"]
false
.For inputArray = ["ab", "bb", "aa"]
, the output should be
solution(inputArray) = true.
It’s possible to arrange these strings in a way that each consecutive pair of strings differ by 1 character (eg: "aa", "ab", "bb"
or "bb", "ab", "aa"
), so return true
.
Input/Output
[execution time limit] 0.5 seconds (cpp)
[memory limit] 1 GB
[input] array.string inputArray
A non-empty array of strings of lowercase letters.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 10
,
1 ≤ inputArray[i].length ≤ 15
.
[output] boolean
Return true if the strings can be reordered in such a way that each neighbouring pair of strings differ by exactly one character (false otherwise).
思路:
这个问题可以使用图的遍历来解决。我们可以把每一个字符串看作图中的一个节点,如果两个字符串只有一个字符不同,那么它们之间就有一条边。我们的目标是找到一个字符串的排列方式,使得相邻的字符串之间都有一条边。
我们可以通过深度优先搜索(DFS)或广度优先搜索(BFS)来遍历图。以下是一种可能的解题思路:
尽管这种解法可能需要遍历整个图,但由于每个字符串只与其他字符串比较一次,因此时间复杂度为 O(n^2),其中 n 是字符串的数量。
上面的遇到相同的字符串处理不了了,失败。
std::next_permutation
可以遍历组合,这个好
int diffByOneChar(string str1, string str2) {
int diff = 0;
for(int i=0;i data) {
for(int i=1;i inputArray) {
std::sort(inputArray.begin(), inputArray.end());
if(check(inputArray)) return true;
while (std::next_permutation(inputArray.begin(), inputArray.end())) {
// for(int i=0;i