Reverse characters of each word in a sentence. For eg:
My name is alex
changes to
yM eman si xela
I thought of the normal O(n)
time algorithm of using two pointer to point to either end of the word and reverse it.
But in the below site
(Refer to ans of ques 2) it is give that converting it to linked list and repetitively applying reversal of linked list for individual word is better. I found the following solution for the same program on Hackerearth:
http://learn.hackerearth.com/question/317/reverse-characters-of-each-word-in-a-sentence/
This solution takes O(n)
time and O(n)
space. The solution I suggested takes O(n)
time O(1)
space. How is the second one better?
Following is the code from Hackerearth:
public node stringReverseChars(node ll){
if(ll == null || ll.next == null)
return ll;
node tmp = ll;
node head = null, prev = null;
while(tmp != null){
while(tmp != null && tmp.data == ' '){
if(head == null)
head = tmp;
prev = tmp;
tmp = tmp.next;
}
if(tmp == null)
break;
node curr = tmp;
while(tmp.next != null && tmp.next.data != ' '){
tmp = tmp.next;
}
node np = tmp.next;
tmp.next = null;
node rev = reverseLL(curr);
if(prev != null)
prev.next = rev;
prev = curr;
curr.next = np;
if(head == null)
head = rev;
tmp = np;
}
return head;
}
I'm pretty skeptical that those other approaches are better. They have worse memory usage (Θ(n) versus O(1)) and worse locality of reference (they use linked lists rather than arrays). I don't see anything wrong with your solution; in fact, I think it's the standard way to do this.
Hope this helps!