LintCode – Space Replacement

Problem: http://www.lintcode.com/en/problem/space-replacement/

Approach:

  1. Calculate spaces
  2. Create a new string with a length equal to the original length plus 2 times the number of spaces.
  3. Use a new string to append char from the end, and replace spaces with %20.
 public int replaceBlank(char[] string, int length) { // write your code here int index =0; int space =0; for(int i=0;i=0;i--){ if(string[i] == ' '){ newstring[index-1] = '0'; newstring[index-2] = '2'; newstring[index-3] = '%'; index = index -3; } else{ newstring[index-1] = string[i]; index --; } } int newlength = newstring.length; return newlength; }

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「LintCode – Space Replacement」

120
0 0 120

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top