|
| 1 | +# 替换空格 |
| 2 | + |
| 3 | +## 题目描述 |
| 4 | + |
| 5 | +请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 |
| 6 | + |
| 7 | +## 调用自带的函数 |
| 8 | + |
| 9 | +``` |
| 10 | +public class Solution { |
| 11 | + public String replaceSpace(StringBuffer str) { |
| 12 | + return str.toString().replace(" ","%20"); |
| 13 | + } |
| 14 | +} |
| 15 | +``` |
| 16 | + |
| 17 | +## 用新的字符串来存储 |
| 18 | + |
| 19 | +``` |
| 20 | +public class Solution { |
| 21 | + public String replaceSpace(StringBuffer str) { |
| 22 | + StringBuffer newStr = new StringBuffer(); |
| 23 | + for(int i=0;i<str.length();i++){ |
| 24 | + char c=str.charAt(i); |
| 25 | + if(' ' == c){ |
| 26 | + newStr.append("%20"); |
| 27 | + }else{ |
| 28 | + newStr.append(c); |
| 29 | + } |
| 30 | + } |
| 31 | + return newStr.toString(); |
| 32 | + } |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +## 在当前字符串上进行替换 |
| 37 | + |
| 38 | +- 先计算替换后的字符串需要多大的空间,并对原字符串空间进行扩容; |
| 39 | + |
| 40 | +- 从后往前替换字符串的话,每个字符串只需要移动一次; |
| 41 | + |
| 42 | +- 如果从前往后,每个字符串需要多次移动,效率较低。 |
| 43 | + |
| 44 | + |
| 45 | +``` |
| 46 | +public class Solution { |
| 47 | + public String replaceSpace(StringBuffer str) { |
| 48 | + int spaceNum=0; |
| 49 | + for(int i=0;i<str.length();i++){ |
| 50 | + if(str.charAt(i)==' '){ |
| 51 | + spaceNum++; |
| 52 | + } |
| 53 | + } |
| 54 | + int oldStrLength=str.length(); |
| 55 | + int newStrLenth=oldStrLength+2*spaceNum; |
| 56 | + str.setLength(newStrLenth); |
| 57 | + int oldStrIndex=oldStrLength-1; |
| 58 | + int newStrIndex=newStrLenth-1; |
| 59 | + for(; oldStrIndex >= 0 && oldStrIndex<newStrIndex; oldStrIndex--){ |
| 60 | + char c=str.charAt(oldStrIndex); |
| 61 | + if(c==' '){ |
| 62 | + str.setCharAt(newStrIndex--,'0'); |
| 63 | + str.setCharAt(newStrIndex--,'2'); |
| 64 | + str.setCharAt(newStrIndex--,'%'); |
| 65 | + }else{ |
| 66 | + str.setCharAt(newStrIndex--,c); |
| 67 | + } |
| 68 | + } |
| 69 | + return str.toString(); |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments