Ugly code. test it for 5+times


  • 0
    Y

    a little ugly code...

    class Solution {
    public:
        bool check(string s)
            {
                int k=0;
                if ((s.length()>1)and(s[0]=='0')) return false;
                for (int i=0;i<s.length();i++)
                k=k*10+int(s[i])-int('0');
                if ((k>=0)and(k<=255)) return true;
                else return false;
            };
        void dfs(string s2,string &s, int nowPos,int nowCount,vector<string> &ans)
            {
                if ((nowCount>4)and(nowPos>s.length()-1))
                {
                    ans.push_back(s2);
                    return;
                }
                if (nowCount>4) return;
                string t1;
                for (int i=0;i<=2;i++)
                if (nowPos+i<s.length())
                {
                    t1=t1+s[nowPos+i];
                    if (check(t1))
                    {
                        if (nowCount==1) dfs(t1,s,nowPos+i+1,2,ans);
                        else dfs(s2+'.'+t1,s,nowPos+i+1,nowCount+1,ans);
                    }
                    
                }
            };    
        vector<string> restoreIpAddresses(string s) {
            int n = s.length();
            vector<string> ans;
    
            dfs("",s,0,1,ans);
            return ans;
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.