leetcode第六题Z字形变换七题八题

第六题: 

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1) return s;
        vector<string> rows(min(numRows,int(s.size())));
        int curRow=0;
        bool goingDown=false;

        for(char c:s){
            rows[curRow]=rows[curRow]+c;
            if(curRow==0||curRow==numRows-1)goingDown=!goingDown;
            curRow+=goingDown?1:-1;
        }
        //vector<string> ret;
        string ret;
        for(string row:rows) ret=ret+row;
        return ret;
    }
};

第七题:整数反转:

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

时间复杂度:O(log(x)),xx 中大约有 log 10 (x) 位数字。空间复杂度:O(1)。

7或8是因为最大值2的31次方减一是2147483647,最小值负2的31次方是-2147483648

范围是-2的31次方(尾数是-8)到2的31次方-1(尾数是7)

8.字符串转整数:

class Solution {
public:
    int myAtoi(string str) {
        int i=0,flag=1;
        long res=0;
        while(str[i]==' ')i++;
        if(str[i]=='-')flag=-1;
        if(str[i]=='-'||str[i]=='+')i++;
        for(;i<str.size()&&isdigit(str[i]);i++){
            res=res*10+(str[i]-'0');
            if(res>=INT_MAX&&flag==1) return INT_MAX;
            if(res>INT_MAX&&flag==-1) return INT_MIN;
        }
        return flag*res;
    }
};

class Automaton {
    string state = "start";
    unordered_map<string, vector<string>> table = {
        {"start", {"start", "signed", "in_number", "end"}},
        {"signed", {"end", "end", "in_number", "end"}},
        {"in_number", {"end", "end", "in_number", "end"}},
        {"end", {"end", "end", "end", "end"}}
    };

    int get_col(char c) {
        if (isspace(c)) return 0;
        if (c == '+' or c == '-') return 1;
        if (isdigit(c)) return 2;
        return 3;
    }
public:
    int sign = 1;
    long long ans = 0;

    void get(char c) {
        state = table[state][get_col(c)];
        if (state == "in_number") {
            ans = ans * 10 + c - '0';
            ans = sign == 1 ? min(ans, (long long)INT_MAX) : min(ans, -(long long)INT_MIN);
        }
        else if (state == "signed")
            sign = c == '+' ? 1 : -1;
    }
};

class Solution {
public:
    int myAtoi(string str) {
        Automaton automaton;
        for (char c : str)
            automaton.get(c);
        return automaton.sign * automaton.ans;
    }
};

猜你喜欢

转载自blog.csdn.net/yangtuoi/article/details/106603421