替換空格
問題描述
力扣鏈接
請實現一個函數,把字符串 s 中的每個空格替換成"%20"。
解決方案
暴力搜索,後移
通過循環整個字符串,每找到一個空格,替換成“%20”,字符串後面的字符往後移動3位。時間複雜度O(n2)。方法不好。
雙指針法(自編碼)
1:先找到字符串(s1)中所有的空格數,這樣就能直到替換後字符串的長度(s2),s2.length() = s1.length() + count*2;
2:從s1字符串的末尾位字符開始判斷是否爲空格,如果是,從後往前向s2字符串中寫入“%20”,s2的下標先前移動三位,s1的下標向前移動一位;如果不是,將字符從s1複製到s2,下標都前移一位。
3:如果兩個下標相等,說明s1字符串前面已經沒有空格了。直接將前面相同的字符複製即可。
class Solution {
public String replaceSpace(String s) {
int count = 0; //空格數量計數器
//統計空格的數量
String s1 = s;
while(s1.contains(" ")){
s1 = s1.substring(s1.indexOf(" ")+1);
count++;
}//s1這樣處理後會變短,所以不要處理形參
//計算將空格轉換成%20後字符串長度
int counttrans = s.length() + count*2-1; //替換後長度
int counts = s.length()-1;
char[] transstring = new char[counttrans+1];
//while(counts <= counttrans && counts >1){
while(count >=0 && counttrans > counts){
if(s.charAt(counts) != ' '){
transstring[counttrans] = s.charAt(counts);
counttrans--;
}else{
transstring[counttrans--] = '0';
transstring[counttrans--] = '2';
transstring[counttrans--] = '%';
}
counts--;
}
//將前面沒有空格的字符串替複製到另一個數組
for(int i=0;i<=counttrans;i++){
transstring[i] = s.charAt(i);
}
String re = new String(transstring);
return re;
}
}
時空複雜度都是:O(n);
搜索問題及答案
如何確定字符串中某個字符的個數:
1.可以利用for循環遍歷
public class lengthIsIncludeSpace {
public static void main(String[] args) {
String s1 = "1 2 m";
int count2 = 0;
for(int i=0;i<s1.length();i++){
if (s1.charAt(i) == ' ')
count2++;
}
System.out.println(count2);
}
}
2.其他方法:
利用map,鍵值與數值對應:鏈接
上面代碼中方案:注意會改變原字符串,但是這個還可以統計子字符串。子字符串統計
如何獲取字符串中某個指定下標的字符
string.charAt(i);
區別於indexOf()
public int indexOf(int ch): 返回指定字符在字符串中第一次出現處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
建立特定長度的數組
char[] str = new char[10];
設定字符串中特定下標位置的字符
需要利用StringBuilder構造字符串,然後使用setCharAt(index, char)即可。index:位置,char:想要替換的字符。最後使用toString()在轉換成字符即可。String類中沒有直接方法能夠設置某個位置的字符。
如何轉換字符數組和字符串
字符數組到字符串:
String string = new String(array);
String string2 = String.valueOf(array);
字符串到字符數組:
String msg = "i am a good boy!";
char[] dest = msg.toCharArray();
官方解法
class Solution {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(char c : s.toCharArray())
{
if(c == ' ') res.append("%20");
else res.append(c);
}
return res.toString();
}
}
利用StringBuild構造器。代碼解釋