將一個字符串中的空格替換成 "%20"。編程
Input: "A B" Output: "A%20B"
要求在原字符串上改動,要將空格替換成 "%20",即每有1個空格字符串長度增長2;app
1.先給原字符串擴展長度,每有1個空格長度增長2個單位spa
2.用雙指針法,指針p2指向擴展後字符串尾,指針p1指向原字符串的尾,從後往前遍歷指針
若p1==空格時,p2依次往前填充"02%";若p1!=空格,p2填充p1指向的字符;雙指針繼續往前遍歷.code
public class Solution { public String replaceSpace(StringBuffer str) { int p1=str.length()-1; for(int i=0;i<=p1;i++){ if(str.charAt(i)==' ') str.append(" "); } int p2=str.length()-1; while(p1>=0&&p2>p1){ char c=str.charAt(p1--); if(c==' '){ str.setCharAt(p2--,'0'); str.setCharAt(p2--,'2'); str.setCharAt(p2--,'%'); }else{ str.setCharAt(p2--,c); } } return str.toString(); } }