Created
January 30, 2018 19:56
-
-
Save jianminchen/1f2f589f620cb2c369e8c723be05b693 to your computer and use it in GitHub Desktop.
sentence reverse - in place - code review and I am the interviewer Jan. 29, 2018 10:00 PM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class Solution { | |
static char[] reverseWords(char[] arr) { | |
if(arr == null || arr.length <= 1){ | |
return arr ; | |
} | |
int len = arr.length ; | |
reverse(arr, 0, len-1); | |
int left = 0, right = 0; | |
while(left < len && right < len){ | |
char current = arr[right]; | |
if(current == ' ' || right == len-1) //handle single word | |
{ //found a word | |
int end = current == ' '? right - 1 : right; | |
reverse(arr, left, end); //reverse chars in the word | |
left = right+1; //move to next word | |
} | |
right++ ; | |
} | |
return arr ; | |
} | |
static void reverse(char[] arr, int start, int end){ | |
int i=start, j=end; | |
while(i<j){ | |
char temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp ; | |
i++; | |
j--; | |
} | |
} | |
public static void main(String[] args) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment