File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -144,6 +144,41 @@ public static String replaceSpace(StringBuffer str) {
144
144
}
145
145
return sb.toString();
146
146
}
147
+
148
+ //方式二:双指针法
149
+ public String replaceSpace(String s) {
150
+ if(s == null || s.length() == 0){
151
+ return s;
152
+ }
153
+ //扩充空间,空格数量2倍
154
+ StringBuilder str = new StringBuilder();
155
+ for (int i = 0; i < s.length(); i++) {
156
+ if(s.charAt(i) == ' '){
157
+ str.append(" ");
158
+ }
159
+ }
160
+ //若是没有空格直接返回
161
+ if(str.length() == 0){
162
+ return s;
163
+ }
164
+ //有空格情况 定义两个指针
165
+ int left = s.length() - 1;//左指针:指向原始字符串最后一个位置
166
+ s += str.toString();
167
+ int right = s.length()-1;//右指针:指向扩展字符串的最后一个位置
168
+ char[] chars = s.toCharArray();
169
+ while(left>=0){
170
+ if(chars[left] == ' '){
171
+ chars[right--] = '0';
172
+ chars[right--] = '2';
173
+ chars[right] = '%';
174
+ }else{
175
+ chars[right] = chars[left];
176
+ }
177
+ left--;
178
+ right--;
179
+ }
180
+ return new String(chars);
181
+ }
147
182
```
148
183
149
184
You can’t perform that action at this time.
0 commit comments