python剑指offer替换空格_《剑指offer》2-替换空格【Java+Python】
替換空格
1. 題目描述
請實現一個函數,將一個字符串中的空格替換成“%20”。
2. 示例
例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
3. 解題思路
此題比較簡單
第一種方法:新開一個內存空間,遍歷原字符串數組,如果碰到字符為空格,則append %20進新的空間
第二種方法:不開辟新的空間,首先統計空格數量,從而計算出新的空間大大小,從后面往前面移動。
4. Java實現
方法一:新開一個內存空間
// 新開一個內存空間
public class Solution {
public String replaceSpace(StringBuffer str) {
//創建一個新的空間
StringBuffer out = new StringBuffer();
for (int i = 0; i < str.length(); i++){
char a = str.charAt(i);
if (a == ' '){
out.append("%20");
}else{
out.append(a);
}
}
return out.toString();
}
}
方法二:不開辟新的空間,從后面往前面移動
public class Solution {
public String replaceSpace(StringBuffer str) {
// 計算空格的數量
int spaceNum = 0;
for (int i = 0; i < str.length(); i++){
char a = str.charAt(i);
if (a == ' '){
spaceNum ++;
}
}
// 開辟空間
int oldIndex = str.length()-1; // 原字符串的下標
int newLength = str.length() + spaceNum * 2;
int newIndex = newLength -1;
str.setLength(newLength); // 重新設置字符串的長度
while(newIndex >= 0){
if (str.charAt(oldIndex) != ' '){
str.setCharAt(newIndex, str.charAt(oldIndex));
oldIndex --;
newIndex --;
}else{
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
oldIndex--; // 只進行一次減 1
}
}
return str.toString();
}
}
5. Python實現
方法一:下列的字符串是 不可變對象,使用 + 操作時,會產生許多的對象,所以最好使用第二種方法
class Solution():
def replaceSpace(self, s):
if type(s) != str:
return
new_s = ''
for sr in s:
if sr == ' ':
new_s += '%20'
else:
new_s += sr
return new_s
so = Solution()
s = ' ab c d e '
print(so.replaceSpace(s))
# %20ab%20c%20d%20e%20
print(s.replace(' ', '%20'))
方法二:轉換成列表形式
class Solution:
def replaceSpace(self, s):
if type(s) != str:
return
li = list(s)
for i in range(len(li)):
if li[i] == ' ':
li[i] = '%20'
res = "".join(li)
return res
so = Solution()
s = ' ab c d e '
print(so.replaceSpace(s))
如果您覺得本文有用,請點個“在看”
總結
以上是生活随笔為你收集整理的python剑指offer替换空格_《剑指offer》2-替换空格【Java+Python】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序直接控制I/O方式
- 下一篇: python问题关键词匹配算法_pyth