自学内容网 自学内容网

10.10 LeetCode 3285 3280 3274

leetcode 3285

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    vector<int> stableMountains(vector<int>& height, int threshold) {
        vector<int> ans;
        for(int i=1; i<height.size(); i++){
            if(height[i-1] > threshold){  //判断下标为 i 山是否稳定
                ans.push_back(i);
            }
        }
        return ans;
    }
};

leetcode 3280

在这里插入图片描述
在这里插入图片描述

思路如下:

先定义转化为二进制的函数

进行切割前,先找到切割位置,即 “-” 的位置,记录下来

切割字符串,年月日

将字符串类型转化为数字类型

class Solution {
public:

    string to_binary(int x){
        stringstream res;  // 可变长字符串

        while(x){
            res << char((x % 2) + '0');   //加 '0' 变成字符  (int + char = int) 强制转换
            x = x / 2;
        }

        string r = res.str();
        reverse(r.begin(), r.end());

        return r;
    }

    string convertDateToBinary(string date) {
        string year = "";
        string month = "";
        string day = "";
        int n = date.length();
        vector<int> pos;   // 动态数组:记录 “-” 的位置
        for(int i=0; i<n; i++){
            if(date[i] == '-'){
                pos.push_back(i);
            }
        }

        year = date.substr(0, pos[0]);
        month = date.substr(pos[0] + 1, pos[1] - pos[0] -1);
        day = date.substr(pos[1] + 1, n - pos[1] - 1);

        int y = stoi(year);
        int m = stoi(month);
        int d = stoi(day);

        string ans = to_binary(y) + "-" + to_binary(m) + "-" + to_binary(d);
        return ans;

    }
};

注:
(1)可变长字符串
定义可变长字符串:stringstream res; // 可变长字符串
写入:res << char((x % 2) + '0');
取出:string r = res.str();

(2)类型强制转换:char((x % 2) + '0')
int + char = int —> char

(3)翻转(reverse)reverse(r.begin(), r.end());
数组(数组、动态数组、字符串)

(4)切割(substr):year = date.substr(0, pos[0]);

(5)字符串类型转化为数字类型:int y = stoi(year);

leetcode 3274

在这里插入图片描述
在这里插入图片描述
思路如下:
先写一个函数来获取每个字符串所表示的颜色

将给的字符串进行拆分,得到行列,找规律得到颜色

class Solution {
public:
    //获取字符串表示的颜色
    // 1 表示为白
    // 2 表示为黑
    int get_color(string id){
        char col = id[0];
        char row_char = id[1];
        int row =  row_char - '0';

        if(id[0] == 'a' || id[0] == 'c' || id[0] == 'e' || id[0] == 'g'){
            if(row%2 == 0){
                return 1;
            }
            else{
                return 2;
            }
        }
        else{
            if(row%2 == 0){
                return 2;
            }
            else{
                return 1;
            }
        }
        return 0;
    }
    
    bool checkTwoChessboards(string coordinate1, string coordinate2) {
        int color1 = get_color(coordinate1);
        int color2 = get_color(coordinate2);
        // if(color1 == color2) return true;
        // else return false;
        return color1 == color2;
    }
};

注:
(1)row 为 int 类型,可以通过两个字符相减得到。

char row_char = id[1];
int row =  row_char - '0';

原文地址:https://blog.csdn.net/weixin_49538228/article/details/142832174

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!