【字符串】1309. 解码字母到整数映射

【题目】
给你一个字符串 s,它由数字(‘0’ - ‘9’)和 ‘#’ 组成。我们希望按下述规则将 s 映射为一些小写英文字符:
字符(‘a’ - ‘i’)分别用(‘1’ - ‘9’)表示。
字符(‘j’ - ‘z’)分别用(‘10#’ - ‘26#’)表示。
返回映射之后形成的新字符串。
题目数据保证映射始终唯一。
【示例 1】
输入:s = “10#11#12”
输出:“jkab”
解释:“j” -> “10#” , “k” -> “11#” , “a” -> “1” , “b” -> “2”.
【示例 2】
输入:s = “1326#”
输出:“acz”
【示例 3】
输入:s = “25#”
输出:“y”
【示例 4】
输入:s = “12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#”
输出:“abcdefghijklmnopqrstuvwxyz”
【提示】
1 <= s.length <= 1000
s[i] 只包含数字(‘0’-‘9’)和 ‘#’ 字符。
s 是映射始终存在的有效字符串。
【代码】
【C++】
执行用时:
0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:
6.2 MB, 在所有 C++ 提交中击败了86.38%的用户

class Solution {
public:
    string freqAlphabets(string s) {
        string strlist[]={"","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        int pre=0,pos=1,flag=(s[s.size()-1]=='#');
        string tempstr="",rs="";
        while(pos!=-1){
            pos=s.find('#',pos+1);
            tempstr=s.substr(pre,pos-pre);
            if(pos==-1)
                break;
            pre=pos+1;
            for(int i=0;i<tempstr.size()-2;i++)
                rs+=strlist[tempstr[i]-'0'];
            int temp=(tempstr[tempstr.size()-2]-'0')*10+(tempstr[tempstr.size()-1]-'0');
            rs+=strlist[temp];
        }
        if(pre<s.size())
            for(int i=0;i<tempstr.size();i++)
                rs+=strlist[tempstr[i]-'0'];
        return rs;
    }
};

【Python】

class Solution:
    def freqAlphabets(self, s: str) -> str:
        strlist=['','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        rs=""
        pos=s.find("#")
        while pos!=-1:
            temp=s[:pos]
            while len(temp)>2:
                rs+=strlist[int(temp[0])]
                temp=temp[1:]
            rs+=strlist[int(temp)]
            s=s[pos+1:]
            pos=s.find("#")
        if s is not None:
            while len(s)>0:
                rs+=strlist[int(s[0])]
                s=s[1:]
        return rs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值