LeetCode 58: Length of Last Word
題目說明:給一個字串目溉,裡面可能包含英文字母(alphabets) 與空格(space)∧苷妫回傳最後一個單字(word)的長度消约。
例如: "Hello World ", 應(yīng)回傳 5, 因為 World 的長度為 5。
TDD 開始
Step 1, 新增測試用例鸟顺。長度為2, 不含空格的 word。 s 為
"bc"
【測試代碼】
【尚未實作的生產(chǎn)代碼】
public class Solution
{
public int LengthOfLastWord(string s)
{
throw new NotImplementedException();
}
}
Step 2, hard-code return
s.Length
, 通過測試
【生產(chǎn)代碼】先 hard-code return s.Length
, 後面的代碼總用得到 s.Length
的器虾。
【重構(gòu)測試】將驗證方法擷取出來
Step 3, 新增測試用例讯嫂,結(jié)尾帶多個空格。s 為
"bc "
【測試代碼】
【生產(chǎn)代碼】先 TrimEnd()
再取 Length
兆沙。
Step 4, 新增測試用例欧芽,s 由兩個 word 組成,中間含空格葛圃。 s 為
"bc xyz"
【測試代碼】
【生產(chǎn)代碼】:從後面找回來,找到第一個空格库正,就知道最後一個 word 的長度曲楚。
Step 5, 新增測試用例, s 最前面從空格開始龙誊。 s 為
" a"
【測試代碼】
【生產(chǎn)代碼】調(diào)整 for loop 邊界
【重構(gòu)】如果 TrimEnd()
得先巡覽一次 s 而浪費無謂的效能,試著在同一個 for loop 中處理掉結(jié)尾的空白喷楣。透過 isEndSpaceClear
判斷是否已經(jīng)走完 s 結(jié)尾的空白趟大。
【重構(gòu)】rename & extract method
最終生產(chǎn)代碼
public class Solution
{
public int LengthOfLastWord(string s)
{
var isEndSpaceClear = false;
var endCharIndex = s.Length - 1;
for (int i = s.Length - 1; i >= 0; i--)
{
if (!isEndSpaceClear && !IsSpace(s[i]))
{
isEndSpaceClear = true;
endCharIndex = i;
}
else if (isEndSpaceClear && IsSpace(s[i]))
{
return endCharIndex - i;
}
}
return isEndSpaceClear ? endCharIndex + 1 : 0;
}
private static bool IsSpace(char @char)
{
return @char == ' ';
}
}
通過 LeetCode 上所有測試用例
結(jié)論
我還是比較喜歡 TrimEnd()
完找第一個空格的寫法,好讀很多铣焊。TrimEnd()
耗的效能逊朽,就賴給 .NET Framework 吧,哈粗截!
GitHub commit history: LeetCode58_LengthOfLastWord