문자열의 단어 순서를 뒤집기(reverse)
문자열의 단어 순서를 뒤집기(reverse)
예) do or not을 not or do로 reverse
- Ref.] LeetCode – Reverse Words in a String (Java)
https://www.programcreek.com/2014/02/leetcode-reverse-words-in-a-string-java/
- Code
예) do or not을 not or do로 reverse
- Ref.] LeetCode – Reverse Words in a String (Java)
https://www.programcreek.com/2014/02/leetcode-reverse-words-in-a-string-java/
- Code
public class Solution {
public String reverseWords(String s) {
if (s == null || s == "") {
return "";
}
String[] strSplitedArr = s.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = strSplitedArr.length -1 ; i >=0 ; i--) {
if (strSplitedArr[i].trim().length() > 0) {
sb.append(strSplitedArr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.toString().substring(0, sb.length() -1);
}
}