java - Reverse words of a char[]/sentence in place -
i want reverse words of string in place using constant space. catch words cannot contain consecutive whitespaces. want reduce consecutive whitespaces between words 1 whitespace , ignore leading , trailing whitespaces. able implement in place reversal of words, i'm struggling implement removing consecutive whitespaces between words , leading , trailing whitespaces. can me?
here have far:
public char[] reversewords(char[] s) { if (s == null) return null; int right = 0; s = reversestring(s, 0, s.length - 1);// reversed sentence //system.out.println(s); (int left = 0; left < s.length; left++) { if (s[left] != ' ') {// first word (right = left; right < s.length && s[right] != ' '; right++) ; // end of word s = reversestring(s, left, right - 1); left =(right - 1);// move left index end of // word // s[left++] = ' '; } } return s; } public char[] reversestring(char[] strchars, int start, int end) { if (strchars == null) return null; while (start < end) { char temp = strchars[start]; strchars[start] = strchars[end]; strchars[end] = temp; start++; end--; } return strchars; }
there going easier/faster ways. giving thought should in learning purpose.
first, whatever have now, reverse words, , leave consecutive space untouched.
then write method consecutive space removing.
have 2 pointer, start @ first position not space.
a , b keep on moving on together.
if (a != b), s[a] = s[b]; s[b] = ' ';
if s[a] , s[a-1] space, stop (a @ 2nd space), , b continue moving forward. such way, stay same position , continue copy b, until b gives non-space character.
and ends when b hit end.
in psuedo code, like
int = first position of non-space; int b = a; while b < s.size() { if (a != b) { s[a] = s[b] s[b] = ' ' } if (both s[a] , s[a-1] space) { increment b; // leave untouched } else { increment a; increment b; } } constant space, o(n) time
another way, can handle removal of consecutive space in place when reversing words:
the hint is, include spaces when doing reverse.
e.g. given string
abc def ghi l (left) first reverse trivial skipping it. hint is, second word, going stop l @ position right after first space:
cba def ghi l the "right" side of reverse going first right boundary of word:
cba def ghi l r then reverse in place
cba fed ghi l r then keep on finding next position of l start reverse again:
cba fed ghi l take similar logic
cba fed ghi l r then
cba fed ihg l r
Comments
Post a Comment