【题目】
给你一个字符串 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