Cracking the Coding Interview Q1.4
2014-07-03 09:37
337 查看
Write a method to replace all spaces in a string with ‘%20’.
Solution:
package chapter1; /** * Write a method to replace all spaces in a string with ‘%20’. (Assume string * has sufficient free space at the end) * * @author jd * */ public class Q1_4 { /** * 1. Count the number of spaces during the first scan of the string. * 2.Parse the string again from the end and for each character: * if a space is encountered, store '%20'; * else store the character as it is in the newly shifted location. */ public static void replaceSpaces(char[] str, int length) { if (str == null) return; int spaceCount = 0; for (int i = 0; i < str.length; i++) { if (str[i] == ' ') spaceCount++; } int newLength = length + 2 * spaceCount; for (int i = length - 1, j = newLength - 1; i >= 0 && j >= 0; i--) { if (str[i] != ' ') { str[j--] = str[i]; } else { str[j--] = '0'; str[j--] = '2'; str[j--] = '%'; } } } public static void main(String[] args) { String str = "abc d e f"; char[] arr = new char[str.length() + 3 * 2 + 1]; for (int i = 0; i < str.length(); i++) { arr[i] = str.charAt(i); } replaceSpaces(arr, str.length()); System.out.println("\"" + new String(arr) + "\""); } }
Solution:
public static void replaceSpaces(char[] str, int length) { int spaceCount = 0, index, i = 0; for (i = 0; i < length; i++) { if (str[i] == ' ') { spaceCount++; } } index = length + spaceCount * 2; str[index] = '\0'; for (i = length - 1; i >= 0; i--) { if (str[i] == ' ') { str[index - 1] = '0'; str[index - 2] = '2'; str[index - 3] = '%'; index = index - 3; } else { str[index - 1] = str[i]; index--; } } }
相关文章推荐
- cracking the coding interview No1.4
- Cracking The Coding Interview 3rd -- 1.4
- Cracking The Coding Interview 1.4
- 《Cracking the Coding Interview》——第4章:树和图——题目7
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目1
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目10
- [Cracking the Coding Interview] Chapter 2 - Linked Lists
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目5
- Cracking the coding interview--Q15.3
- Cracking the coding interview--Q16.1-Q16.10
- Cracking the coding interview 第一章问题及解答
- Cracking The Coding Interview3.4 暂存
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q1.8
- 【Cracking the coding interview】Q1.2(反转字符串)
- 技术面试圣经《Cracking the Coding Interview》题解C++版
- Cracking The Coding Interview
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目5
- 《Cracking the Coding Interview》——第13章:C和C++——题目6
- 《Cracking the Coding Interview》——第14章:Java——题目2