Reverse Words in a String Java Solution - The Coding Shala
Home >> Interview Questions >> Reverse Words in a String
Reverse Words in a String
Problem:
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: " hello world! "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Note:
A word is defined as a sequence of non-space characters.
The input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. You need to reduce multiple spaces between two words to a single space in the reversed string.
Reverse Words in a String Java Solution
Approach:
Better to use StringBuilder instead of + to make a new string.
trim() is used to remove leading and trailing zeros.
Java
class Solution { public String reverseWords(String s) { s=s.trim(); int len = s.length()-1; StringBuilder ans = new StringBuilder(); while(len >= 0){ while(len>=0 && s.charAt(len)==' ') len--; int index = s.lastIndexOf(' ', len); if(index == -1){ ans.append(s.substring(0,len+1)); }else{ ans.append(s.substring(index+1, len+1)).append(" "); } len = index - 1; } return ans.toString(); } }
Other Posts You May Like
Comments
Post a Comment