题目来源:
leetcode题目,网址:1592. 重新排列单词间的空格 - 力扣(LeetCode)
解题思路:
遍历数组,对空格和单词数计数,然后按要求将空格和单词添加至结果中即可。
解题代码:
class Solution {
public String reorderSpaces(String text) {
int wordNum=0;
int spaceNum=0;
for(int i=0,pre=-1;i<text.length();i++){
if(text.charAt(i)==' '){
spaceNum++;
}
if(pre==-1 && text.charAt(i)!=' '){
pre=0;
wordNum++;
}else if(pre==0 && text.charAt(i)==' '){
pre=-1;
}
}
int space=wordNum==1?0:spaceNum/(wordNum-1);
StringBuffer res=new StringBuffer();
for(int i=0,count=0;i<text.length() && res.length()<text.length();i++){
if(text.charAt(i)==' ' &&res.length()==0){
continue;
}
if(text.charAt(i)!=' '){
while(i<text.length() && text.charAt(i)!=' '){
res.append(text.charAt(i));
i++;
}
i--;
}else if(text.charAt(i)==' '){
while(i<text.length() && text.charAt(i)==' '){
i++;
}
if(i>=text.length()){
break;
}
for(int j=0;j<space;j++){
res.append(" ");
}
count++;
i--;
}
}
for(int i=res.length();i<text.length();i++){
res.append(" ");
}
return res.toString();
}
}
总结:
代码写得好烂。
官方题解得思路也是模拟,但代码比我得漂亮很多。
String.trim() 去除字符串得首位空格。
正则表达式 "\\s+" 中 "\s"匹配空白符,+表示匹配上一个字符匹配一个到无穷个。