1.面试题 01.03.URL化
题目描述:
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-url-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
class Solution {
public:
string replaceSpaces(string S, int length) {
string p;
p.resize(length * 3 + 1);
int i = 0, j = 0;
for(j = 0; j < length; j++)
{
if(S[j] == ' ')
{
p[i] = '%';
p[i+1] = '2';
p[i+2] = '0';
i += 3;
}
else
{
p[i] = S[j];
i++;
}
}
p = p.substr(0,i);
return p;
}
};
2.重新排列字符串 1528
题目描述:
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
string S(s);
string::size_type i, k = s.size();
for(i = 0; i < k; i++)
{
int j = 0;
j = indices[i];
S[j] = s[i];
}
return S;
}
};