Created
May 25, 2017 04:46
-
-
Save jianminchen/256b85d6b933ce1eb0222835c900497f to your computer and use it in GitHub Desktop.
Sentence reverse - mocking experience
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ReverseSentence | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(reverseWords("perfect makes practice".ToCharArray())); | |
} | |
static char[] reverseWords(char[] arr) | |
{ | |
// your code goes here | |
if (arr == null || arr.Length == 0) | |
{ | |
return new char[0]; | |
} | |
reverseString(arr, 0, arr.Length - 1); // | |
// reverse each word | |
reverseEachWord(arr); | |
return arr; | |
} | |
/// <summary> | |
/// | |
/// </summary> | |
/// <param name="arr"></param> | |
private static void reverseEachWord(char[] arr) | |
{ | |
int length = arr.Length; | |
int start = 0; // "a ", "ab b " | |
for (int i = 0; i < length; i++) | |
{ | |
var visit = arr[i]; | |
bool visitIsSpace = visit == ' '; | |
var startChar = arr[start]; | |
bool startIsSpace = startChar == ' '; | |
if (startIsSpace) | |
{ | |
start = i; // mark the word start | |
} | |
bool isLastChar = i == (length - 1); | |
bool foundWord = !startIsSpace && visitIsSpace; // "ab ", "ab cd" " practice" | |
bool foundWordCase1 = (foundWord && (i - 1 - start) >= 0); | |
bool foundWordCase2 = !startIsSpace && !visitIsSpace && isLastChar; | |
if (foundWordCase1 || foundWordCase2) | |
{ | |
var end = isLastChar ? i : (i - 1); // bug in mocking experience, missing isLastChar end = i instead of i - 1. | |
reverseString(arr, start, end); | |
start = i + 1; // start new word | |
} | |
} | |
} | |
private static void reverseString(char[] arr, int start, int end) | |
{ | |
if (start >= end) | |
{ | |
return; | |
} | |
while (start < end) | |
{ | |
var tmp = arr[start]; | |
arr[start] = arr[end]; | |
arr[end] = tmp; | |
start++; | |
end--; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment