• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
93. Restore IP Addresses

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) {
        int l = s.length(), c, t, ls, idx, i;
        vector<string> ans;
        if(l < 4 || l > 12)
            return ans;
        string str;
        queue<string> q;
        q.push(str);
        queue<int> pntq; //number of points
        pntq.push(0);
        while(!q.empty())
        {
            str = q.front();
            q.pop();
            c = pntq.front();
            pntq.pop();
            ls = str.length();
            for(i = 0, t = 0; i < 3; i++)
            {
                idx = ls - c + i;
                t = t * 10 + s[idx] - '0';
                if(t > 255)
                    break;
                if(l-idx-1 >= 3-c && l-idx-1 <= 3*(3-c))
                {
                    string ts = str + s.substr(ls-c, i+1);
                    if(c < 3)
                    {
                        ts += ".";
                        q.push(ts);
                        pntq.push(c+1);
                    }
                    else
                    {
                        ans.push_back(ts);
                    }
                }
                if(0 == i && '0' == s[idx]) //注意不能出现010之类以0开头的子串
                    break;
            }
        }
        return ans;
    }
};
注意不能出现010之类以0开头的子串
posted on 2016-04-06 14:40  ArgenBarbie  阅读(133)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3