Learn-dsa..in 30 days!



























CC-17 : Reverse the characters of individual words in the String.

Description:

: Given a String, reverse the order of characters of individual words within of the String and return the same.

Test cases and expected outputs:

Input Parameters Expected outputs
The original string is:
Java is the best
The reversed words chars are:
avaJ si eht
The original string is:
Data structures and algorithms using Java
The reversed words chars are:
ataD serutcurts dna smhtirogla gnisu avaJ

Pseudocode:

Initialize a Deque stack for processing purposes.
For all characters in input String str:
If current character is not a space add it to the stack.
If current character is a space it means we have found a space between word.
While stack is not empty, pop characters out of the stack and append to String variable called wrrd.
When the above while loop is completed, variable wrrd contains contains characters of current word in reversed order.
Append wrrd to revStr.
Append a space to revStr to maintain spacing between words.
After above for loop completes, the last word of input String will not contain a space at the end. So, using while loop again pop characters out of the stack and append to String variable called wrrd. Append wrrd to revStr.
Return revStr.


Code:

public String reverseWordsChars(String ipStr) throws Exception{
	Deque<Character> stack=new LinkedList<Character>();
	String wrrd=""; 
	char[] chars=ipStr.toCharArray();
	String str="";
	for (int idx=0; idx < chars.length; idx++) {
		if (chars[idx] != ' ') {
			stack.addFirst(chars[idx]);
			
		} else {
				while(stack.size() !=0) {
					wrrd=wrrd+stack.pollFirst();
				}
				if (str.length() !=0) {str=str+" ";}
			str=str+wrrd;
			wrrd="";			
		}	
	}	
	while(stack.size() !=0) {
			wrrd=wrrd+stack.pollFirst();
		}
	str=str+" "+wrrd;
	return str;
}

Click here to download and run code and test cases !