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