前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode刷题系列/1

leetcode刷题系列/1

作者头像
用户9831583
发布2022-06-16 16:11:01
2270
发布2022-06-16 16:11:01
举报
文章被收录于专栏:码出名企路

1,整数反转

示例:

输入

输出

123

321

-123

-321

120

21

实现:

代码语言:javascript
复制
#include <iostream>
using namespace std;
#include  <climits>//INT_MAX

int main()
{
    int x=123;
    int res=0;
    do{
        if(res>INT_MAX/10 || res<INT_MIN/10)//判断溢出
            return 0;
        res = res*10 + x%10;
    }while(x/=10);

    cout<<res<<endl;
}

2,回文数

示例:

输入

输出

121

正序倒序都一样,是

-121

正序倒序不一样,不是

实现:

代码语言:javascript
复制
#include <iostream>
using namespace std;
#include  <climits>//INT_MAX

//搞后一半就行 与前一半比较是否相等

int main()
{
    bool ress=false;
    int  input=123321;
    //当input<0,最后一位是0第一位也得是0,所以只有0
    if(input<0 || (input%10==0 && input!=0))
        return false;

     int res=0;
    do{
        if(res>INT_MAX/10 || res<INT_MIN/10)//判断溢出
            return false;
        res = res*10 + input%10;
        input/=10;
    }while(input > res);
    
    //当输入的长度为奇数 res/10去除中位的数字 最中间的数字不影响回文的判断
    ress = (input == res || input ==res/10);

    cout<<ress<<endl;
}

3,有效的括号

示例:

输入

输出

(){}[]

前后闭合,有效

({[[})

前后闭合,有效

{]

前后不闭合,无效

实现:

代码语言:javascript
复制
int main()
{
    string input="({[]})";
    unordered_map<char,char> match = {{'(',')'},{'{','}'},{'[',']'}};
    int n=0;
    while(n<input.size())
    {    
        cout<<"1"<<input[n]<<" "<<match[input[n]]<<" "<<input[n+1]<<endl;
        if(match[input[n]] == input[n+1] && input[n+1] != '\0')
        {
            input.erase(n,2);//
            n=-1;
        }
        n++;
    }
    cout<<!input.size()<<endl;
}

//辅助栈,效率高
#include <iostream>
using namespace std;
#include <unordered_map>
#include <string>
#include <stack>

int main()
{
    string input="({[]})";
    unordered_map<char,char> match = {{')','('},{'}','{'},{']','['}};
    stack<char> re;
    cout<<re.empty()<<endl;
    bool result;
    for(char in:input)
    {   
         cout<<in<<" "<<match[in]<<endl;
        if(in=='(' || in=='{' || in=='[')
            re.push(in);
        else
        {    
            if(re.empty() || re.top() != match[in])
                result=0;
            else
                re.pop();
        }
    }
    result=re.empty();
    cout<<result<<endl;
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码出名企路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档