【题目】
给你一个字符串 s,它由数字(‘0’ - ‘9’)和 ‘#’ 组成。我们希望按下述规则将 s 映射为一些小写英文字符:
字符(‘a’ - ‘i’)分别用(‘1’ - ‘9’)表示。
字符(‘j’ - ‘z’)分别用(‘10#’ - ‘26#’)表示。
返回映射之后形成的新字符串。题目数据保证映射始终唯一。
来源:leetcode
链接:https://leetcode-cn.com/problems/decrypt-string-from-alphabet-to-integer-mapping/
【示例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 是映射始终存在的有效字符串
【代码】
class Solution {
public:
string str[27]={"","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"};
string freqAlphabets(string s) {
int pos=s.find("#");
while(pos>=2&&pos<=1000){//先对#进行处理
int num=(s[pos-2]-'0')*10+(s[pos-1]-'0');
s.replace(pos-2,3,str[num]);
pos=s.find("#");
}//得到一个不包含#的字符串
for(auto &x:s)
if(x>='0'&&x<='9')
x=str[x-'0'][0];
return s;
}
};
【知识点】
string& replace (size_t pos, size_t len, const string& str);
string s="hello";
s.replace(0,2,"123");//把字符串“hello”的前两个字符“he”替换成“123”
cout<<s<<endl;//“123llo”