王争算法学习打卡0307-0314
- 面试题 01.03. URL化:https://leetcode-cn.com/problems/string-to-url-lcci/
class Solution:
def replaceSpaces(self, S: str, length: int) -> str:
if length == 0:
return
s = ""
temp = S[0: length]
for i in temp:
if i == " ":
s += "%20"
else:
s += i
return s
2. 1528. 重新排列字符串:https://leetcode-cn.com/problems/shuffle-string/
自己的错误思路
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
char temp[indices.size()];
char res[indices.size()];
strcpy(temp, s.c_str());
for(int i = 0; i < indices.size(); i++){
res[indices[i]] = temp[i];
}
return res;
}
};
正确答案
class Solution {
public:
string restoreString(string s, vector<int>& indices) {
int len = s.length();
string res(len, 0);
for(int i = 0; i < len; i++){
res[indices[i]] = s[i];
}
return res;
}
};
本题思路其实是一样的,只不过正确答案直接在string上操作,没有多余的转换,并且把s的大小直接给了一个常数,方便后续操作。