Convert numeric string to IP address Apare

Convert numeric string to IP address

Niuke link <–


Title description

Now there is a string containing only numbers, convert the string into the form of an IP address, and return all possible situations.
For example: the
given string is "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (The order does not matter)

Input:
"25525511135"

Output
["255.255.11.135","255.255.111.35"]

Function interface regulations:

class Solution {
    
    
public:
    /**
     * 
     * @param s string字符串 
     * @return string字符串vector
     */
    vector<string> restoreIpAddresses(string s) {
    
    
    	//write your code here
    }
};

This topic has been encountered in the interview before, and there are still some circumstances to consider. First, we need dfs to divide the string into 4 parts. Because IPv4 is 32 bits, it is divided into abcd using dotted decimal notation. Each decimal number must be in the range of [0,255]. So when we dfs, we can first ensure that the digits of each number are between 1 and 3.
After dfs is divided, it is necessary to judge whether the decimal number is legal. If it is an empty string, it must not work, if there is a leading zero, it will not work, and it will not work if it is greater than 255.

class Solution {
    
    
public:
    /**
     * 
     * @param s string字符串 
     * @return string字符串vector
     */
    string tmp;
    int r[4];
    int ok(string s) {
    
     //判断十进制串是否合法
    	if(!s.length()) return -1; //空串
    	if((int)s.length()>1 && s[0]=='0') return -1; //有前导零
    	int ans = 0;
    	for(int i=0;i<(int)s.length();++i) {
    
    
    		ans = ans * 10 + s[i]-'0';
		}
		if(ans>255) ans = -1; 
		return ans;
	} 
    string judge() {
    
     //判断这种分隔方案是否可行
        string a = tmp.substr(0,r[1]+1);
        string b = tmp.substr(r[1]+1,r[2]-r[1]);
        string c = tmp.substr(r[2]+1,r[3]-r[2]);
        string d = tmp.substr(r[3]+1);
       	string res = "#";
        if(ok(a)!=-1 && ok(b)!=-1 && ok(c)!=-1 && ok(d)!= -1) {
    
    
			res = a+"."+b+"."+c+"."+d; 
		}
		return res; 
    }
    void dfs(int x,vector<string>& vans) {
    
    
        if(x==4) {
    
    
            string res = judge();
            if(res!=string("#")) vans.push_back(res);
            return;
        }
        for(int i=1;i<=3;++i) {
    
    
        	if(r[x-1]+i>=(int)tmp.length()) return; //后面的串分配不到字符了
            r[x] = r[x-1]+i;
            dfs(x+1,vans);
        }
    }
    vector<string> restoreIpAddresses(string s) {
    
    
        tmp = s;
        vector<string> ans;
        r[0] = -1;
        dfs(1,ans);
        return ans;
    }
};

Use r[] to record the subscript of the last element of each string in the original string. Then, for each scheme produced by dfs, the legality of the four substrings is judged, and if it is legal, it is recorded.

Guess you like

Origin blog.csdn.net/qq_40531479/article/details/108745052