博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LinkCode-空格替换
阅读量:4155 次
发布时间:2019-05-25

本文共 887 字,大约阅读时间需要 2 分钟。

空格替换

设计一种方法,将一个字符串中的所有空格替换成 %20 。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。

样例

对于字符串”Mr John Smith”, 长度为 13

替换空格之后的结果为”Mr%20John%20Smith”

注意

如果使用 Java 或 Python, 程序中请用字符数组表示字符串。

挑战

在原字符串(字符数组)中完成替换,不适用额外空间

问题分析:

在原字符串上进行操作,那么就是在检测到’ ‘时,把字符串数组i位置后面的元素右移两位.然后插入”%20”.
时间复杂杂度O(n);空间复杂度O(1);

代码:

public class Solution {
/** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ public int replaceBlank(char[] string, int length) { int k=0; for (int i = 0; i < length+k; i++) { if(string[i]==' '){ for(int j= length+k-1;j>i;j--){ string[j+2]=string[j]; } k=k+2; string[i]='%'; string[i+1]='2'; string[i+2]='0'; } } return length+k; }}

转载地址:http://pvwxi.baihongyu.com/

你可能感兴趣的文章
第六章 背包问题——01背包
查看>>
51nod 分类
查看>>
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
性能扩展问题要趁早
查看>>
MySQL-数据库、数据表结构操作(SQL)
查看>>
OpenLDAP for Windows 安装手册(2.4.26版)
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
JSP的内置对象及方法
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Spring MVC和Struts2的比较
查看>>
Hibernate和IBatis对比
查看>>