LeetCode_Restore IP Address

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

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> ans;
    	if (s == "" || s.length() > 12)
    	{
    		return ans;
    	}
    	string vS[4];
    	RestoreIPDFS(ans, vS, 0, s, 0);
    	return ans;
    }
    
        
    void RestoreIPDFS(vector<string> &ans, string vS[], int count, string &s, int step)
    {
        if (count == 4)
    	{
    		if (step == s.length())
    		{
    			string str = vS[0];
    			for (int i = 1; i < 4; ++i)
    			{
    				str += '.';
    				str += vS[i];
    			}
    			ans.push_back(str);
    		}
    		return;
    	}
    	// 如果當前s中剩餘的長度爲[4-count, 3*(4-count)]則可以
    	int remain = s.length() - step;
    	if ((remain >= (4 - count)) && (remain <= (12 - 3 * count)))
    	{// 此次解析i個字符
    		for (int i = 1; i <= min(3, remain); ++i)
    		{
    			string tmp = s.substr(step, i);
    			// 如果長度不爲0,則第一個不能爲0
    			if (i > 1 && tmp[0] == '0')
    			{
    				continue;
    			}
    			if (atoi(tmp.c_str()) <= 255)
    			{
    				vS[count] = tmp;
    				RestoreIPDFS(ans, vS, count + 1, s, step + i);
    			}
    		}
    	}
    }
};


發佈了134 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章