LeetCode刷题实战433:最小基因变化
示例
示例 1:
start: "AACCGGTT"
end: "AACCGGTA"
bank: ["AACCGGTA"]
返回值: 1
示例 2:
start: "AACCGGTT"
end: "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
返回值: 2
示例 3:
start: "AAAAACCC"
end: "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
返回值: 3
解题
class Solution {
private:
unordered_set<string> st;
bool find_end(string& str, string& end, queue<string>& que) {
vector<char> next({'A', 'C', 'T', 'G'});
for (int m = 0; m < str.size(); m++) {
string new_str = str;
for (int n = 0; n < 4; n++) {
new_str[m] = next[n];
if (new_str == end) {
return true;
}
if (st.count(new_str)) {
que.push(new_str);
st.erase(new_str);
}
}
}
return false;
}
public:
int minMutation(string start, string end, vector<string>& bank) {
st = unordered_set<string>(bank.begin(), bank.end());
if (st.count(end) == 0) {
return -1;
}
queue<string> que;
que.push(start);
int res = 0;
while (!que.empty()) {
res++;
int size = que.size();
for (int i = 0; i < size; i++) {
string str = que.front();
que.pop();
if (find_end(str, end, que)) {
return res;
}
}
}
return -1;
}
};
LeetCode刷题实战426:将二叉搜索树转化为排序的双向链表