剑指Offer----替换空格
来源:互联网 发布:网上购物商城源码ssh 编辑:程序博客网 时间:2024/05/01 22:14
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
多种方法,第一种新建一个StringBuffer tostr,从头到尾遍历待替换字符串,当遇到空格时,在tostr后面添加“%20”,当遇到非空格时,将遍历字符串的当前字符添加到tostr后面;
public class Solution { public String replaceSpace(StringBuffer str) { if(str==null||str.length()<=0)return ""; StringBuffer tostr=new StringBuffer(); for(int i=0;i<str.length();i++){ if(str.charAt(i)==' ')tostr.append("%20"); else tostr.append(str.charAt(i)); } return tostr.toString(); }}第二种方法,使用String的replace方法
public class Solution { public String replaceSpace(StringBuffer str) { if(str==null||str.length()<=0)return ""; return str.toString().replace(" ","%20"); }}
第三种方法,先获取总的空格数量,然后将待替换字符串长度扩充为 原来的长度+2*空格数量,设立两个指针,一个是原待替换字符串末尾p,一个是扩充后字符串末尾q,依次向前遍历,当待替换字段遇到空格时,指针p前移一位,指针q依次前移赋值为02%,前移三位,直到p,q指针相遇或者到达字符串头部。
public class Solution { public String replaceSpace(StringBuffer str) { if(str==null||str.length()<=0)return ""; int oldlength=str.length(); int banknumber=0; for(int i=0;i<oldlength;i++){ if(str.charAt(i)==' ')banknumber++; } int newlength=oldlength+2*banknumber; int p=oldlength-1; int q=newlength-1; str.setLength(newlength); while(p>=0&&q>p){ if(str.charAt(p)==' '){ str.setCharAt(q--,'0'); str.setCharAt(q--,'2'); str.setCharAt(q--,'%'); } else str.setCharAt(q--,str.charAt(p)); p--; } return str.toString(); }}
阅读全文
0 0
- [剑指offer]替换空格
- [剑指offer]替换空格
- 剑指offer:替换空格
- 替换空格--《剑指offer》
- 剑指Offer:替换空格
- 【剑指offer】替换空格
- 《剑指Offer》--替换空格
- 剑指offer--替换空格
- 【剑指offer】替换空格
- 【剑指offer】空格替换
- 剑指offer-替换空格
- 剑指offer:替换空格
- [剑指offer]替换空格
- 《剑指offer》替换空格
- 剑指offer:替换空格
- 【剑指Offer】替换空格
- 【剑指offer】-替换空格
- 剑指offer 替换空格
- react-native Alert组件
- 整数转换成罗马数字 python
- bzoj 1045: [HAOI2008]糖果传递
- zookeeper的简单使用
- 剑指offer——平衡二叉树
- 剑指Offer----替换空格
- UVaThe Dragon of Loowater-11292(排序+贪心)
- Maven的配置文件pom.xml
- 二值图像腐蚀与膨胀操作样例
- bzoj1856: [Scoi2010]字符串
- 身体训练
- 剑指offer:字符串的排列
- epoll讲解
- React Native自定义控件【底部抽屉菜单】