算法题(String)----持续更新

1、给定一个字符串,解析出所有可能的IP地址。

例如输入:"25525511135"。

那么输出应该为:["255.255.11.135", "255.255.111.35"]。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        string str;
        help(res, s ,str ,0, 0);
        return res;
    }
private:
    void help(vector<string> & res, const string & s, string & str, int cur, int loop) {
        if(cur == s.length() && loop == 4) {
            res.push_back(str.substr(0, str.length() - 1));
            return ;
        } else if(loop >= 4) {
            return ;
        }
        for(int i = 1; i <= 3 && (cur + i) <= s.length(); ++i) {
            string ss = s.substr(cur,i);
            int num = stoi(ss);
            if(ss[0] == '0' && ss.length() > 1) {
                break;
            }
            if(num >= 0 && num <= 255) {
                str += ss;
                str += ".";
                help(res, s, str, cur + i, loop + 1);
                str.erase(str.length() - i - 1);
            }
        }
    }
};

2、验证UTF-8

给定一个int型的数组,判断是否为一个合法的UTF-8编码的序列。每个int元素只有最后一个字节有效。关于UTF-8的编码规则可自行谷歌。

class Solution {
public:
    bool validUtf8(vector<int>& data) {
        int count = 0;
        for (auto c : data) {
            if (count == 0) {
                if ((c >> 5) == 0b110) count = 1;
                else if ((c >> 4) == 0b1110) count = 2;
                else if ((c >> 3) == 0b11110) count = 3;
                else if ((c >> 7)) return false;
            } else {
                if ((c >> 6) != 0b10) return false;
                count--;
            }
        }
        return count == 0;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_22158743/article/details/88836171
今日推荐