您的位置:首页 > 编程语言 > Go语言

[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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: