35 lines
1.1 KiB
Java
35 lines
1.1 KiB
Java
|
package com.zerroi.leetcode.Three14;
|
||
|
|
||
|
public class ReverseWords {
|
||
|
public static void main(String[] args) {
|
||
|
SolutionSecond solutionSecond = new SolutionSecond();
|
||
|
String res = solutionSecond.reverseWords("a good example");
|
||
|
System.out.println("res = " + res);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class SolutionSecond {
|
||
|
public String reverseWords(String s) {
|
||
|
StringBuilder builder = new StringBuilder();
|
||
|
int startIndex = 0;
|
||
|
int endIndex = s.length() - 1;
|
||
|
for (; startIndex < s.length(); startIndex++) {
|
||
|
if (s.charAt(startIndex) != ' ') break;
|
||
|
}
|
||
|
for (; endIndex >= 0; endIndex--) {
|
||
|
if (s.charAt(endIndex) != ' ') break;
|
||
|
}
|
||
|
int cur = endIndex;
|
||
|
for (; startIndex <= endIndex; endIndex--) {
|
||
|
if (s.charAt(endIndex) == ' ') {
|
||
|
if (s.charAt(endIndex + 1) != ' ') {
|
||
|
builder.append(s, endIndex + 1, cur + 1).append(" ");
|
||
|
}
|
||
|
cur = endIndex - 1;
|
||
|
}
|
||
|
}
|
||
|
builder.append(s, startIndex, cur + 1);
|
||
|
return builder.toString();
|
||
|
}
|
||
|
}
|