剑指offer——替换空格
来源:互联网 发布:昆明设计软件培训 编辑:程序博客网 时间:2024/06/06 01:17
书中第三题
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:主要问题在于复杂度,从前往后进行空格寻找并替换,复杂度更高,因为字符移动的次数更多。
从后往前,字符移动的次数更少,复杂度更低。
以及不要产生过多的对象。
public class Solution { public String replaceSpace(StringBuffer str) { int spacenum = 0;//spacenum为计算空格数 for(int i=0;i<str.length();i++){ if(str.charAt(i)==' ') spacenum++; } int indexold = str.length()-1; //indexold为为替换前的str下标 int newlength = str.length() + spacenum*2;//计算空格转换成%20之后的str长度 int indexnew = newlength-1;//indexnew为为把空格替换为%20后的str下标 str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界 for(;indexold>=0 && indexold<indexnew;--indexold){ if(str.charAt(indexold) == ' '){ // str.setCharAt(indexnew--, '0'); str.setCharAt(indexnew--, '2'); str.setCharAt(indexnew--, '%'); }else{ str.setCharAt(indexnew--, str.charAt(indexold)); } } return str.toString(); }}
阅读全文
0 0
- 剑指offer—替换空格
- 剑指offer—替换空格
- 《剑指offer》——替换空格
- 《剑指offer》——替换空格
- 剑指offer——替换空格 C++
- 剑指Offer——替换空格
- 《剑指offer》——替换空格
- 剑指offer——字符串空格替换
- 剑指Offer——替换空格
- 替换空格——剑指offer
- 剑指offer —— 替换空格
- 剑指offer——替换空格
- 剑指offer——替换空格
- 剑指offer——空格替换
- 剑指offer——替换空格
- 剑指offer——替换空格
- 剑指offer——2.替换空格
- 剑指offer刷题—替换空格
- Netty结合WebSocket实现简单网页聊天室
- 剑指offer 面试题49 把字符串转换成整数
- Kotlin 基本语法
- Fragment did not create a view
- 如何学好C语言
- 剑指offer——替换空格
- Kotlin 基本类型
- LeetCode_2、6两题
- git忽略文件夹或文件
- 红尘客栈
- Pythontip 输出字典key
- PAT--1036. Boys vs Girls
- SpringSide实战(三)----使用SpringSide4自动构建一个项目
- 戴尔·卡耐基(美)《演讲的艺术》