题解 | #数字字符串转化成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以内,递归即可。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:00
点赞 评论 收藏
分享
ohs的小木屋:比不少实习待遇高了
点赞 评论 收藏
分享
缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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