劍指offer替換空格
阿新 • • 發佈:2018-12-18
python的簡單,甚至都沒理解題意就稀裡糊塗做出來了
# -*- coding:utf-8 -*-
class Solution:
# s 源字串
def replaceSpace(self, s):
# write code here
res = ''
for i in s:
if i == ' ':
res += '%20'
else:
res += i
return res
Java的,好吧我也沒看出來,也稀裡糊塗做出來了
class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replaceAll("\\s", "%20");
}
}
最後想了下,可能不是用replace吧,
class Solution { public String replaceSpace(StringBuffer str) { String stri = str.toString(); char[] strchr = stri.toCharArray(); StringBuffer res = new StringBuffer(); for(int i = 0;i<strchr.length;i++){ if(strchr[i]==' '){res.append("%20");} else{res.append(strchr[i]);} }return res.toString(); } }
嗯,這題是考的String,StringBuffer和char的使用,沒錯