Issue
I want to make a program to reverse the words only, not the letters.
For example...
i love india
... should become...
india love i
Another example...
google is the best website
... should become...
website best the is google
With spaces I have thoroughly researched on it but found just nothing.
My logic is that I should just give you my program that is not working. If you find a small error in my code please give the solution for it and a corrected copy of my program. Also, if you are not too busy, can you please give me the logic in a flow chart.
Thank you for your time.
Solution
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
// split to words by space
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
Answered By - vk1
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)