Anjan Dutta
Leet Code 557: Reverse Words in a String III
Leet Code 557: Reverse Words in a String III
Problem statement:
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Constraints:
- 1 <= s.length <= 5 * 104
- s contains printable ASCII characters.
- s does not contain any leading or trailing spaces.
- There is at least one word in s.
- All the words in s are separated by a single space.
Solution:
/** * @param {string} s * @return {string} */var reverseWords = function(s) { let st = 0; let en = 0; s=s.split(''); let len = s.length; for(let i=0;i<len;i++) { if(s[i]==" " && st<en) { rev(s,st,en-1); st=en+1; } else if(i==s.length-1 && st<en){ rev(s,st,en); st=en+1; } en++; } return s.join('');}
function rev(str,l,r) { while(l<r){ let tmp = str[l]; str[l] = str[r]; str[r] = tmp; l++; r--; }}