题解 | #数字字符串转化成IP地址#

数字字符串转化成IP地址

https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e

#include <functional>
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return string字符串vector
     */
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        function<void(int, int, string)> dfs = [&](int idx, int cnt, string path) -> void {
            if (cnt == 4 || idx == s.length()) {
                if (cnt == 4 && idx == s.length()) {
                    path.pop_back();
                    res.push_back(path);
                }
                return;
            }
            string tmp;
            if (s[idx] == '0') {
                dfs(idx + 1, cnt + 1, path + "0.");
                return;
            }
            for (int i = idx; i < s.length(); ++i) {
                tmp += s[i];
                if (stoi(tmp) > 255) break;
                dfs(i + 1, cnt + 1, path + tmp + ".");
            }
        };
        dfs(0, 0, "");
        return res;
    }
};

思路:递归。

将每一段控制在255以内,递归即可。

全部评论

相关推荐

鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务