1、URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。
(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
链接:https://leetcode-cn.com/problems/string-to-url-lcci
/**
* URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。
* (注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
* 链接:https://leetcode-cn.com/problems/string-to-url-lcci
*
* @param str
* @param length
* @return
*/
public String replaceSpaces(String str, int length) {
char[] chars = new char[length * 3];
int j = 0;
for (int i = 0; i < length; i++) {
if (str.charAt(i) == ' ') {
chars[j++] = '%';
chars[j++] = '2';
chars[j++] = '0';
} else {
chars[j++] = str.charAt(i);
}
}
return new String(chars, 0, j);
}
2、给你一个字符串 s 和一个 长度相同 的整数数组 indices 。请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。返回重新排列后的字符串。
(例:“abc”,[3,2,1] "cba")
链接:https://leetcode-cn.com/problems/shuffle-string
/**
* 给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
* 请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
* 返回重新排列后的字符串。
* 链接:https://leetcode-cn.com/problems/shuffle-string
*
* @param str
* @param indices
* @return
*/
public String restoreString(String str, int[] indices) {
char[] chars = new char[indices.length];
for (int i = 0; i < indices.length; i++) {
chars[indices[i]] = str.charAt(i);
}
return new String(chars);
}