給定一個只包含數字的字符串,復原它並返回所有可能的 IP 地址格式。
示例:
輸入: "25525511135"
輸出: ["255.255.11.135", "255.255.111.35"]
DFS,思路:考慮滿足ip地址的要求,必須放置三個點 " . ",將字符串分割成4段。
於是我們可以遍歷每個字符間隔放置 " . " 的前一個字串是否滿足要求,如果滿足,則
繼續放置 ".",存儲合法字串,一直到最後用完3個".",之後判斷尾部的字符串就可以了,
如果不滿足,拋棄當前上一個字串,重新遍歷 "."的位置。
這裏我說明一下,爲什麼當前不滿足,要拋棄上一個已經合法的字串,大家可以看我寫的JudgeIsIp 函數,其實出現違法的情況就只有下面幾種:
1.字符串長度大於3。(雖然判了小於0的情況,但是根據遞歸順序,字符串字串不可能小於0)
2.字符串數字大於255。
3.字符串大於1且首字母爲0。
如果滿足這三個條件是一定無法構成ip地址的,並且隨着遞歸順序增加,"."的位置只會到更後邊,本次循環的下一個字串必定非法,所以沒畢業繼續進行本次循環,return,滿足上一個合法字符穿字串的操作已經進入遞歸,所以上一個合法字符字串必須捨棄,重新排列。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> son;
backtrace(s, 0, 0, son);
return m_res;
}
/*
* s : 原始字符
* start: 起始位
* count: 分割的次數
* son : 字符串子串
*
*/
void backtrace(string s, int start, int count, vector<string>& son) {
if (count < 3) {
for (int i = start + 1; i < s.length(); i++) {
string temp = s.substr(start, i - start);
/* 不滿足條件,pop */
if (!JudgeIsIp(temp)) {
if (!son.empty())
son.pop_back();
return;
}
vector<string> tmp(son);
tmp.push_back(temp);
backtrace(s, i, count + 1, tmp);
}
}
/* 判斷最後一位 */
else if (count == 3) {
string temp = s.substr(start, s.length() - start);
/* 不滿足條件,pop */
if (!JudgeIsIp(temp)) {
if (!son.empty())
son.pop_back();
return;
}
son.push_back(temp);
string res;
for (int i = 0; i < son.size(); i++) {
res += son[i] + ".";
}
string last = res.substr(0, res.length() - 1);
m_res.push_back(last);
}
}
private:
vector<string> m_res;
/* 判斷是否是ip地址 */
bool JudgeIsIp(string& ip) {
if (ip.length() <= 0 || ip.length() > 3) {
return false;
}
if (atoi(ip.c_str()) > 255) {
return false;
}
if (ip.length() > 1 && ip[0] == '0') {
return false;
}
return true;
}
};
int main() {
string str = "25525511135";
Solution* ps = new Solution();
vector<string> x = ps->restoreIpAddresses(str);
vector<string>::iterator it = x.begin();
while (it != x.end()) {
cout << *it << endl;
it++;
}
return 0;
}