剑指Offer之替换空格
来源:互联网 发布:王朔浮出海面 知乎 编辑:程序博客网 时间:2024/05/08 12:10
本身难度并不大,java一个replace();就可以了,或者另外开辟一个String,遍历一遍也是可行的,但是出发点并不是A题,而是考虑性能,程序在空间还有时间上的使用以及程序的鲁棒性,不过九度上的测试数据还真是大char数组要开到10^6次方。
普通的就不说了,介绍一下书中的方法。
假设str="We Are Happy";设置两个指针p1,p2。初始化为0.p1指的是原长度,p2指的是替换空格之后的。遍历一遍如果不算'\0'结尾符的话,p1=12,p2=16;
然后进行赋值操作,将p1指向的元素赋给p2,p1--,p2--。直到p1遇到一个空格,此时将“%20”插入到p2之前,p2-=3.p1--。重复操作,直到p1==p2。说明不再有空格。
其中C是上述方法,c++是另外开辟一个string。
java:
import java.util.Scanner;public class Main {public static void main(String[] arges) {Scanner in = new Scanner(System.in);while (in.hasNextLine()) {String str = null;str = in.nextLine();System.out.println(str.replace(" ", "%20"));}}}
c++:
#include <stdio.h>#include <iostream>#include <string>#include <string.h>using namespace std;int main(){ //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin); string templet="%20"; char str[1000000]; int n; while(gets(str)) { getchar(); string s=""; n=strlen(str); for(int i=0;i<n;i++) { if(str[i]==' ') { s+=templet; } else { s+=str[i]; } } cout<<s<<endl; } return 0;}
c:
#include <stdio.h>int main(){ //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin); char str[1000000]; int p1,p2; while(gets(str)) { //getchar(); p1=0; p2=0; for(int i=0;str[i]!='\0';i++) { p1++; p2++; if(str[i]==' ') p2+=2; } while(p1>=0&&p1!=p2) { if(str[p1]!=' ') { str[p2]=str[p1]; p2--; p1--; } else{ str[p2--]='0'; str[p2--]='2'; str[p2--]='%'; p1--; } } printf("%s\n",str); } return 0;}
0 0
- 剑指Offer之替换空格
- 剑指Offer之 - 替换空格
- 剑指offer之替换空格
- 剑指offer之空格替换
- 剑指offer之替换空格
- 剑指offer之替换空格
- 剑指offer之替换空格
- 《剑指offer》之替换空格
- 剑指offer之 替换空格
- 剑指offer之替换空格
- 剑指offer之替换空格问题
- 剑指offer面试题之替换空格
- 码农小汪-剑指Offer之5 -替换空格
- 剑指offer之替换字符串中的空格
- 剑指offer(四)之替换空格
- 剑指Offer之字符串空格替换问题
- (二)剑指Offer之替换空格
- 剑指offer之空格替换java
- Android平台好友点击微信分享的内容后跳转来源App的实现方案研究
- C++ Primer Plus学习笔记
- quick-cocos2dx中使用pomelo
- java专题——卡特兰数
- android 尺寸适配相关
- 剑指Offer之替换空格
- JS+CSS实现的鼠标滑过列表行渐变色效果
- String 比较
- secureCRT vim 出现乱码
- 随机森林
- nyoj11奇偶数分离
- Xcode5 制作工程模版教程
- I/O模型之Select模型
- Apache负载均衡之Apache proxy和Apache+mod_jk方式