qingcheng奕  

https://oj.leetcode.com/problems/restore-ip-addresses/

string到int的ip地址格式化。

分别用 i+1,j+1,k+1,表示前三个地址段的数位的个数。之后判断每个地址段是否数字个数都是从1到3,并且数是从0到255,符合条件的即可。

如果一个地址段的第一位是0,则这个地址段只能是0.比如 010010,表示成0.10.0.10或者0.100.1.0

class Solution {
public:
    int str2int( string str)
    {
        if(str[0]=='0'&& str.size()>1)
            return 270; //this is 01,010 and so on , no allowed 
        // if the first bit is 0 ,then it no allowed second bit
        int ans = 0;
        for(int i = 0;i<str.size();i++)
        {
            ans = ans*10;
            ans += str[i] - '0';
        }
        return ans;
    }
    vector<string> restoreIpAddresses(string s) {
        string strAnsPiece;
        vector<string> ans;
        if(s.size()>12 || s.size()<4)
            return ans;
    
        for(int i = 0;i<=2;i++)
        {
            string str1 = s.substr(0,i+1);
            if(s.size()-i-1>9)
                continue;
            if(str2int(str1)>255)
                break;
            
            for(int j = 0;j<=2;j++)
            {
                if( s.size() - i - j - 2 >6)
                    continue;
                string str2 = s.substr(i+1,j+1);
                if(str2int(str2)>255)
                    break;
                
                for(int k = 0;k<=2;k++)
                {
                    string str3 = s.substr(i+j+2,k+1);
                    if(str2int(str3)>255)
                        break;
                    if((s.size() - i - j - k - 3 >=1 )&& (s.size() - i - j - k - 3 <=3 ))
                    {
                        string str4 = s.substr(i+j+k+3,s.size()-i-j-k-3);
                        if(str2int(str4)<=255)
                        {
                            string ansPiece = str1;
                            ansPiece.append( "."); 
                            ansPiece.append(str2);
                            ansPiece.append( ".");
                            ansPiece.append(str3);
                            ansPiece.append(".");
                            ansPiece.append(str4);
                            ans.push_back(ansPiece);
                        }
                    }

                }
            }
        }
        return ans;
    }
};

 

posted on 2014-06-21 20:27  qingcheng奕  阅读(155)  评论(0编辑  收藏  举报