1、面试题 01.03. URL化:https://leetcode-cn.com/problems/string-to-url-lcci/
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
class Solution {
public String replaceSpaces(String S, int length) {
char[] chs = S.toCharArray();
int i = length-1,j = S.length()-1;
while(i >= 0){
if(chs[i] == ' '){
chs[j--] = '0';
chs[j--] = '2';
chs[j--] = '%';
}else{
chs[j--] = chs[i];
}
i--;
}
return String.valueOf(chs,j+1,S.length()-j-1);
}
}
2、1528. 重新排列字符串:https://leetcode-cn.com/problems/shuffle-string/
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
class Solution {
public String restoreString(String s, int[] indices) {
char[] chs = new char[s.length()];
for(int i=0;i<indices.length;i++){
chs[indices[i]] = s.charAt(i);
}
return new String(chs);
}
}