Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 99dc852

Browse files
committed
更新了剑指Offer05.替换空格的java双指针解法
1 parent 77c1098 commit 99dc852

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

problems/剑指Offer05.替换空格.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,41 @@ public static String replaceSpace(StringBuffer str) {
144144
}
145145
return sb.toString();
146146
}
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+
}
147182
```
148183

149184

0 commit comments

Comments
 (0)