剑指Offer-【面试题04:替换空格】
2016-11-18 16:49
459 查看
package com.cxz.question4; /* * 请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.” * 原来一个空格字符,替换成%20,字符串会变长 * */ public class Demo4 { /** * * @param string 要转换的字符数组 * @param usedLength 字符数组中已经使用的长度,没转换之前的 * @return 转换后的字符数组长度,-1表示处理失败 */ public static int replaceBlank(char[] string, int usedLength) { //判断输入是否合法 if (string == null || string.length < usedLength) { return -1; } //统计字符数组中的空白字符数 int whiteCount = 0; for (int i = 0; i < usedLength; i++) { if (string[i] == ' ') { whiteCount++; } } //计算转换后的字符长度 int targetLength = whiteCount * 2 +usedLength; int tmp = targetLength; if (targetLength > string.length) { return -1; } if (whiteCount == 0) { return usedLength; } usedLength--; targetLength--; //字符中有空白字符,一直处理到所有的空白字符处理完 while (usedLength >= 0 && usedLength < targetLength) { if (string[usedLength] == ' ') { string[targetLength--] = '0'; string[targetLength--] = '2'; string[targetLength--] = '%'; } else { string[targetLength--] = string[usedLength]; } usedLength--; } return tmp; } public static void main(String[] args) { char[] string = new char[50]; string[0] = 'W'; string[1] = 'e'; string[2] = ' '; string[3] = 'a'; string[4] = 'r'; string[5] = 'e'; string[6] = ' '; string[7] = 'H'; string[8] = 'a'; string[9] = 'p'; string[10] = 'p'; string[11] = 'y'; int length = replaceBlank(string, 12); System.out.println(new String(string, 0, length)); } }
相关文章推荐
- 剑指offer-面试题04-替换空格
- [剑指offer][面试题04]实现一个函数,将字符串中的空格替换为“ ”.例如输入“we are happy.”,输出"we are happy.".
- 剑指Offer面试题4替换空格
- 剑指offer-面试题4-替换空格
- 【剑指Offer学习】【面试题4 : 替换空格】
- 剑指offer,面试题四替换空格
- 剑指Offer:面试题4 替换空格
- 【剑指offer】面试题4:替换空格 java
- 剑指offer-chapter2-面试题4-替换空格(java)
- 剑指Offer学习之面试题4 : 替换空格
- 剑指offer-面试题4 - 替换空格
- 剑指Offer面试题4(Java版):替换空格
- 剑指offer——面试题4:替换空格
- 【剑指offer】面试题四:替换空格
- 剑指offer面试题4 替换空格
- 剑指offer面试题4:替换空格和合并两个有序数组
- 【剑指offer】面试题5:替换空格
- 【剑指Offer面试题】 九度OJ1510:替换空格
- 剑指offer-04:字符串替换空格
- 剑指offer面试题[4]-空格替换