[Google]Rearrange White Spaces
2014-07-27 16:38
197 查看
Question:
Given a string with multiple spaces write a function to in-place trim all spaces leaving a single space between words
e.g.
_ _ _ Hello _ _ _ World _ _ _
Hello _ World _ _ _ _ _ _ _ _ _
Solution:
利用两个指针i,j,i指向当前需要放置字符的位置,j用来寻找要放置的字符.
public static void rearrange(char[] chs)
{
int i=0;
int j=0;
while(i<chs.length)
{
j=notSpace(chs,j);
if(j==chs.length)
{
for(;i<chs.length;i++) chs[i]=' ';
}else
{
while(j<chs.length && chs[j]!=' ') chs[i++]=chs[j++];
if(i<chs.length) chs[i++]=' ';
}
}
System.out.println(chs);
}
public static int notSpace(char[] chs,int begin)
{
while(begin<chs.length)
{
if(chs[begin]!=' ')return begin;
begin++;
}
return begin;
}
Given a string with multiple spaces write a function to in-place trim all spaces leaving a single space between words
e.g.
_ _ _ Hello _ _ _ World _ _ _
Hello _ World _ _ _ _ _ _ _ _ _
Solution:
利用两个指针i,j,i指向当前需要放置字符的位置,j用来寻找要放置的字符.
public static void rearrange(char[] chs)
{
int i=0;
int j=0;
while(i<chs.length)
{
j=notSpace(chs,j);
if(j==chs.length)
{
for(;i<chs.length;i++) chs[i]=' ';
}else
{
while(j<chs.length && chs[j]!=' ') chs[i++]=chs[j++];
if(i<chs.length) chs[i++]=' ';
}
}
System.out.println(chs);
}
public static int notSpace(char[] chs,int begin)
{
while(begin<chs.length)
{
if(chs[begin]!=' ')return begin;
begin++;
}
return begin;
}
相关文章推荐
- rearrange array (red, white, blue)
- Spring配置文件异常:White spaces are required between publicId and systemId
- [LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串
- 去掉新版google reader上方空白 fix Google Reader white space
- Rearrange a string so that all same characters become d distance away
- Rearrange a string so that all same characters become d distance away
- Android SDK安装更新Failed to fetch URL http://dl-ssl.google.com/android/repository/addons_list-2.xml, re
- Rearrange String k Distance Apart
- ZOJ 2625 Rearrange Them(DP)
- shake phone and rearrange workspace apps
- CareerCup Rearrange an array using swap with 0
- Rearrange an array of positive and negative integers
- jsp trimDirectiveWhitespaces ="true"
- Spring配置文件异常:White spaces are required between publicId and systemId
- Rearrange a String With Integers-LintCode
- Follow the Whitespaces 一个诡异的解谜网站
- JSP JSTL EL 删除空行 <%@ page trimDirectiveWhitespaces="true" %>
- GTS:com.google.android.installpackageswhitelist.gts.GtsInstallPackagesWhitelistDeviceTest#testInstal
- White spaces are required between publicId and systemId
- xml操作-Nested exception: org.xml.sax.SAXParseException: White spaces are required between publicId and systemId. 异常处理