Replace Space to %20 in the String
leetcode:https://leetcode.cn/problems/ti-huan-kong-ge-lcof/
Description:
Please implement a function that replaces each space in the string s with “%20”.
Idea:
Solution1:
Step1: build a new empty string
Step2: traverse the string, if the characetr is space. then add the new string with %20, if it’s not the space, add it to the new string
Code:
class Solution {
public String replaceSpace(String s) {
String string1 = "";
for(int i=0; i<s.length(); i++){
if (s.charAt(i) == ' '){
string1 = string1 + "%20";
}
if(s.charAt(i) != ' ')
string1 = string1 + s.charAt(i);
}
return string1;
}
}
in the '' , it only exits character;
in the "", it exits string;
Solution2:
Step1: expand double space(because we need to replace " " to “%20”, so add two space after the string) of the space in the string: creating the new string, if the character of the string is space, add three space to the new string.
Step2: create two pointer. the first one to point the end of original string.
then add the new string to the original string, the second pointer point to end of expanded string.
Step3: if the first pointer == space, then the second pointer will replace the character with %20 by decreasing the index. if the first pointer isn’t equal to space, then make the character that scond pointer pointed equal to the character that first pointer pointed.
Step4: leftmove the first pointer and second pointer, until first pointer equal to the start of the string.
Code:
class Solution {
public String replaceSpace(String s) {
String add = "";
// expand the string
for(int i=0; i<s.length(); i++){
if (s.charAt(i) == ' '){
add += " ";
}
}
// set the first pointer point to the end of original string
int fisrtpointer = s.length()-1;
// expand string and set the second pointer point to the end of the new string
s+=add;
int secondpointer = s.length()-1;
char[] result =s.toCharArray();
while(fisrtpointer>=0){
if(result[fisrtpointer]==' '){
// replace the space with %20, by self decreasing the index; becasue x--, will decrease the value after the operation
result[secondpointer--]= '0';
result[secondpointer--]='2';
result[secondpointer]='%';
}
else{
result[secondpointer]=result[fisrtpointer];
}
fisrtpointer--;
secondpointer--;
}
return new String(result);
}
}