【LeetCode】93. Restore IP Addresses(C++)

地址:https://leetcode.com/problems/restore-ip-addresses/

题目:

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]

理解:

要把输入的字符串转换为所有可能的IP地址

实现:

这种实现非常巧妙
ijkl表示每段的长度,最小为1,最大为3
要保证加起来长度恰好是s的长度
另外,转换完之后长度还不能减小,防止出现有0的情况。

class Solution {
public:
	vector<string> restoreIpAddresses(string s) {
		vector<string> res;
		string ans;
		for (int i = 1; i<=3; ++i) 
			for (int j = 1; j<=3; ++j)
				for (int k = 1; k<=3; ++k)
					for (int l = 1; l <= 3; ++l) {
						if (i + j + k + l == s.length()) {
							int tmp1 = stoi(s.substr(0, i));
							int tmp2 = stoi(s.substr(i, j));
							int tmp3 = stoi(s.substr(i + j, k));
							int tmp4 = stoi(s.substr(i + j + k, l));
							if (tmp1 <= 255 && tmp2 <= 255 && tmp3 <= 255 && tmp4 <= 255)
								if ((ans = to_string(tmp1) + "." + to_string(tmp2) + "." + to_string(tmp3) + "." + to_string(tmp4)).length() == s.length() + 3)
									res.push_back(ans);
						}	
					}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/85000374
今日推荐