[字符串高频题]Leetcode 93

Leetcode 93

题目地址:

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

题目,给定一个字符串,需要划成四份,使得每一份x我都要满足0<= x <= 255,并且不能出现 x = “01”(不能以0开头的串)
e.g. s = “25525511135”
out = [“255.255.11.135”,“255.255.111.35”]
思路:dfs遍历整个字符串,对于每一层dfs来说,记录当前一层的起始位置,记录当下已经被切成几分。退出条件是当切分的数量 > 4就退出,当前的起始位置等于字符串的最后一位的下一位并且切分的数量等于4的时候,就退出。 对每一层dfs来说,需要for循环当前位置以及当前位置的3位,判断这几位是否满足0<=255并且不能存在011的情况,如果满足,那么记录下来进入下一层循环,需要回溯。
注意:由于我判断结束的条件是字符串的最后一位的下一位,所以我需要for循环的遍历中小于等于字符串的长度,不然会导致问题

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        string temp;
        dfs(0, 0, s, temp, ret);
        return ret;
    }

    void dfs(int index, int cnt, string& s, string& temp, vector<string>& ret) {
        if (cnt > 4) {
            return;
        }
        if(index == s.size()) {
            if (cnt == 4) {
                     //delete the dot
                temp = temp.substr(0, temp.size()-1);
                ret.push_back(temp);

            }
            return;
        }
        for(int i = 1; i <= 3 && index + i <= s.size(); i++) {
            string newStr = s.substr(index,i);
            if (newStr[0] == '0' && newStr.size() > 1) {
                break;
            }
            if (stoi(newStr) <= 255) {
                string cur = temp;
                temp += newStr;
                temp += ".";
                dfs(index + i, cnt + 1, s, temp, ret);
                temp = cur;
            }
        }
    }
};

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值