-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
73 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
src/main/java/com/diguage/algo/leetcode/_0151_ReverseWordsInAString.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package com.diguage.algo.leetcode; | ||
|
||
import java.util.Deque; | ||
import java.util.LinkedList; | ||
|
||
public class _0151_ReverseWordsInAString { | ||
// tag::answer[] | ||
|
||
/** | ||
* @author D瓜哥 · https://www.diguage.com | ||
* @since 2024-09-19 17:11:20 | ||
*/ | ||
public String reverseWords(String s) { | ||
Deque<String> stack = new LinkedList<>(); | ||
boolean inWord = false; | ||
for (char c : s.toCharArray()) { | ||
if (c == ' ') { | ||
inWord = false; | ||
} else { | ||
if (!inWord) { | ||
stack.push(String.valueOf(c)); | ||
inWord = true; | ||
} else { | ||
stack.push(stack.pop() + c); | ||
} | ||
} | ||
} | ||
StringBuilder sb = new StringBuilder(s.length()); | ||
while (!stack.isEmpty()) { | ||
sb.append(stack.pop()).append(" "); | ||
} | ||
sb.deleteCharAt(sb.length() - 1); | ||
return sb.toString(); | ||
} | ||
// end::answer[] | ||
} |