Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. /*
  2. * Write a method to replace all spaces in a string with '%20'.
  3. * You may assume that the string has sufficient space at the end
  4. * of the string to hold the additional characters, and that you
  5. * are given the "true" length of the string.
  6. * (Note: if implementing in Java, please use a character array
  7. * so that you can perform this operation in place.)
  8. *
  9. * CC150 1.4 Replace Space
  10. * @author: Scarlett Chen
  11. * @Date: 12/20/2014 Sat 9:28 PM
  12. * 题目建议java用character处理,而且要in place,就是不要用超过1个charArray,只在array内改动。 <--主要的难点
  13. * 这时只能根据替换前后两个不同的CharArray的位置差,在一个CharArray中实现替换。--->通常要从后往前替换。
  14. *
  15. * 题目中表示String最后会有足够的空格空间用于替换,所以我们不必先计算这个String空间是不是够被替换。
  16. * 但是我们需要计算,空间是不是太多了?替换完了以后,是不是还要剩下空格。-->出于这个考虑,我计算了newLength,并最后用了trim
  17. *
  18. */
  19. public class ReplaceSpace {
  20. public String replaceSpace(String s) {
  21. int len = s.length();
  22. if (len <1) return s;
  23. char[] chArray = s.toCharArray();
  24. //trueLength: from 0 to the last not-null character in the original string
  25. //newLength: =trueLength+spaceCount*2, the length after replacement
  26. //spaceCount: Amount of spaces in the String (Spaces at the end of the string is excluded)
  27. while (len-1>=0 && chArray[len-1]==' ') len--;
  28. int trueLength = len;
  29. int spaceCount = 0;
  30.  
  31. for (int i=0; i<trueLength; i++)
  32. if (chArray[i]==' ') spaceCount++;
  33.  
  34. int newLength = trueLength +spaceCount *2;
  35. //利用位置差,从后往前替换。
  36. for (int i=trueLength-1, j=newLength-1; i>=0; i--,j--) {
  37. if (chArray[i]==' ') {
  38. chArray[j--] = '0';
  39. chArray[j--] ='2';
  40. chArray[j] = '%';
  41. }
  42. else chArray[j] = chArray[i];
  43. }
  44. s = String.valueOf(chArray);
  45. return s.trim();
  46. }
  47.  
  48.  
  49. public static void main(String[] args) {
  50. // TODO Auto-generated method stub
  51. ReplaceSpace rs = new ReplaceSpace();
  52. String s =" d ";
  53. System.out.println(rs.replaceSpace(s));
  54.  
  55. }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement