Given an input string
A word is defined as a sequence of non-space characters. The words in
Return a string of the words in reverse order concatenated by a single space.
Note that
s
, reverse the order of the words.A word is defined as a sequence of non-space characters. The words in
s
will be separated by at least one space.Return a string of the words in reverse order concatenated by a single space.
Note that
s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Approach
Java
import java.util.Stack;public class ReverseWords {public static void main(String[] args) {String s = "the sky is blue";System.out.println(reverseWords(s));}static String reverseWords(String s) {int n = s.length();if (n == 0)return "";int i = 0, j = n - 1;while (i < n && s.charAt(i) == ' ')i++;while (j > 0 && s.charAt(j) == ' ')j--;Stack<String> st = new Stack<String>();while (i <= j) {String x = "";while (i <= j && s.charAt(i) != ' ') {x += s.charAt(i);i++;}st.push(x);while (i <= j && s.charAt(i) == ' ')i++;}String res = "";while (!st.isEmpty()) {res += st.pop();if (!st.isEmpty())res += " ";}return res;}}
C++
#include <bits/stdc++.h>using namespace std;string reverseWords(string s){int n = s.size();if (n == 0)return "";int i = 0, j = n - 1;while (i < n && s[i] == ' ')i++;while (j > 0 && s[j] == ' ')j--;stack<string> st;while (i <= j){string x = "";while (i <= j && s[i] != ' '){x += s[i];i++;}st.push(x);while (i <= j && s[i] == ' ')i++;}string res = "";while (!st.empty()){res += st.top();st.pop();if (!st.empty())res += " ";}return res;}int main(){string s = "the sky is blue";cout << reverseWords(s);return 0;}
No comments:
Post a Comment