Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order
Example:
Input: str="Hello world" Output: str="olleH dlrow"
Approach
Java
public class ReverseWordsINStringIII {public static void main(String[] args) {String str = "Hello world";System.out.println(reverseWords(str));}// function to reverse each words in the stringstatic String reverseWords(String s) {int n = s.length();if (n == 0)return "";int i = 0, j = n - 1;// if their are spaces in// start of stringwhile (i < n && s.charAt(i) == ' ')i++;// if their are spaces in the end of stringwhile (j > 0 && s.charAt(j) == ' ')j--;String res = "";// now iterate in remaining stringwhile (i <= j) {StringBuffer x = new StringBuffer();while (i <= j && s.charAt(i) != ' ') {x = x.append(s.charAt(i));i++;}// reveres the current wordx = x.reverse();// add into the resultres += x;if (i < j)res += " ";while (i <= j && s.charAt(i) == ' ')i++;}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to reverse each words in the stringstring reverseWords(string s){int n=s.size();if(n==0)return "";int i=0,j=n-1;//if their are spaces in//start of stringwhile(i<n&&s[i]==' ')i++;//if their are spaces in the end of stringwhile(j>0&&s[j]==' ')j--;string res="";//now iterate in remaining stringwhile(i<=j){string x="";while(i<=j&&s[i]!=' '){x+=s[i];i++;}//reveres the current wordreverse(x.begin(),x.end());//add into the resultres+=x;if(i<j)res+=" ";while(i<=j&&s[i]==' ')i++;}return res;}int main(){string str="Hello world";cout<<reverseWords(str);return 0;}
No comments:
Post a Comment