LeetCode- 93. 复原IP地址

241 篇文章 1 订阅
210 篇文章 0 订阅

给定一个只包含数字的字符串,复原它并返回所有可能的 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值