crack the coding interview 数组与字符串 1.4
来源:互联网 发布:nginx 事件模型 编辑:程序博客网 时间:2024/06/08 05:21
crack the coding interview 数组与字符串 1.4
题目:
将字符串中的空格全部替换为 “%20”
package ac.crack_code_interview.ch01_array_string;import org.junit.Test;import java.util.Arrays;/** * description: * * @author liyazhou * @since 2017-06-27 10:19 * * 9.1 数组与字符串 * * 题目 1.4 * 编写一个方法,将字符串中的空格全部替换为 “%20”。假定该字符串尾部有足够的空间存放 * 新增字符,并且知道字符串的 “真实长度”。 * * 思路: * 1. 计算出处理之后的字符串的长度,然后从右向左依次往后移动 * 2. 统计空格的总个数,计算出处理后的字符串的末尾字符的下标; * 将字符从右向左依次移动; * 遇到空格则依次插入字符 '0','2','%' */public class Test04 { public void replaceSpaces(char[] chars, int len){ int spaceNum = 0; for (char ch : chars){ if (ch == ' ') spaceNum ++; } int newLen = len + spaceNum * 2; for (int i = len-1; i >= 0; i --){ if (chars[i] != ' '){ chars[--newLen] = chars[i]; }else{ chars[--newLen] = '0'; chars[--newLen] = '2'; chars[--newLen] = '%'; } } } @Test public void test(){ String[] strs = { "i am a student.", " it is a good day. ", }; for (String str : strs){ char[] chars = new char[100]; for (int i = 0; i < str.length(); i ++) chars[i] = str.charAt(i); System.out.print(str + "\t"); replaceSpaces(chars, str.length()); System.out.println(new String(chars)); } }}
阅读全文
0 0
- crack the coding interview 数组与字符串 1.4
- crack the coding interview 数组与字符串 1.1
- crack the coding interview 数组与字符串 1.2
- crack the coding interview 数组与字符串 1.3
- crack the coding interview 数组与字符串 1.5
- crack the code interview 1.4
- Crack the Coding Interview[careerup150]正式启动!【倒计时30天】
- Cracking The Coding Interview 1.4
- Cracking the coding interview--问题与解答
- Cracking the coding interview--问题与解答
- Cracking the coding interview--问题与解答
- Cracking the coding interview--问题与解答
- Cracking the coding interview--问题与解答
- Cracking the coding interview--问题与解答
- crack the code interview 1.2
- crack the code interview 1.5
- crack the code interview 1.6
- crack the code interview 1.7
- 查找算法之二分查找
- 自定义View之declare-styleable属性介绍
- request.getParameter和request.getAttribute之间的区别
- 打印报错:找不到类applet.HtmlPrintApplet.class的几种情况
- Python+CRF处理2014年人民日报语料库
- crack the coding interview 数组与字符串 1.4
- 常用正则表达式
- 把《编程珠玑》读薄
- ORMLite 数据库的使用--二次封装
- 【mongoDB实战】聚合管道--$unwind
- SQL树结构
- 面试题34—丑数
- 现在要加强的一些技能,以及以后的发展
- 关于URL和URI