这是取自 pramp 站点,我正在尝试遵循他们的 psudo 代码,这是对以下问题的回答。
**
给定一个字符数组 arr,它由由空格字符分隔的字符序列组成。每个以空格分隔的字符序列定义一个单词。实现一个函数 reverseWords,它以最有效的方式反转数组中单词的顺序。
**
例子:
input: arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]
output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't' ]
这是我的代码。有用。
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
[TestClass]
public class ReverseSentanceTest
{
[TestMethod]
public void ManyWordsTest()
{
char[] inputArray = {
'p', 'e', 'r', 'f', 'e', 'c', 't', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'r', 'a', 'c', 't', 'i', 'c', 'e'
};
char[] expectedOutputArr = {'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ',
'm', 'a', 'k', 'e', 's', ' ',
'p', 'e', 'r', 'f', 'e', 'c', 't'};
char[] outputArr = ReserverseSentence(inputArray);
CollectionAssert.AreEqual(expectedOutputArr, outputArr);
}
[TestMethod]
public void OneWordTest()
{
char[] inputArray = {
'p', 'e', 'r', 'f', 'e', 'c', 't',
};
char[] expectedOutputArr = {
'p', 'e', 'r', 'f', 'e', 'c', 't'};
char[] outputArr = ReserverseSentence(inputArray);
CollectionAssert.AreEqual(expectedOutputArr, outputArr);
}
public char[] ReserverseSentence(char[] inputArr)
{
if (inputArr == null || inputArr.Length == 0)
{
throw new ArgumentException("array is empty");
}
MirrorArray(inputArr, 0, inputArr.Length-1);
int indexStart = 0;
for (int i = 0; i < inputArr.Length; i++)
{
//end of a word in the middle of the sentence
if (inputArr[i] == ' ')
{
MirrorArray(inputArr, indexStart, i - 1);
indexStart = i+1; //skip the white space and start from the letter after
}
else if (i == inputArr.Length - 1)
{
MirrorArray(inputArr, indexStart, i);
}
}
return inputArr;
}
private void MirrorArray(char[] inputArr, int start, int end)
{
while (start < end)
{
var temp = inputArr[start];
inputArr[start] = inputArr[end];
inputArr[end] = temp;
start++;
end--;
}
}
}
}
但是我想我错过了一个角落案例。他们的伪代码有 3 个 if/else 分支。我只是将我的单词初始化为一个整数,他们使用类似的东西nullable<int>
。
function reverseWords(arr):
# reverse all characters:
n = arr.length
mirrorReverse(arr, 0, n-1)
# reverse each word:
wordStart = null
for i from 0 to n-1:
if (arr[i] == ' '):
if (wordStart != null):
mirrorReverse(arr, wordStart, i-1)
wordStart = null
else if (i == n-1):
if (wordStart != null):
mirrorReverse(arr, wordStart, i)
else:
if (wordStart == null):
wordStart = i
return arr
# helper function - reverses the order of items in arr
# please note that this is language dependent:
# if are arrays sent by value, reversing should be done in place
function mirrorReverse(arr, start, end):
tmp = null
while (start < end):
tmp = arr[start]
arr[start] = arr[end]
arr[end] = tmp
start++
end--
你能解释一下我是否遗漏了一些角落案例吗?并举个例子。谢谢 !