Lambda Enumerable Pairwise處理

  • 57
  • 0

Lambda Enumerable Pairwise處理

題目出處 Arcade > Thr Core > 70 Alphabet Subsequence

給定一字串s,回傳s是否為plaintextalphabet的subsequence

(The plaintext alphabet is a string "abcdef...xyz".)

 

在我的解法中要使一個Array的元素兩兩比對 (當然有更簡單的解法不需要這樣做)

想著有沒有不使用迴圈的寫法,最後在stackoverflow找到了一個使用Lambda的技巧

array.Zip(array.Skip(1), (a, b) => ...)

於是套用到程式中,完成

bool alphabetSubsequence(string s) {

    // 先造出plaintextAlphabet字串
    string plaintextAlphabet = new String(Enumerable.Range(0, 26).Select(x => (char)('a' + x)).ToArray());
	
    // 找出給定字串s中各字元在plaintextAlphabet的位置
    // 避免Lazy Execute浪費效能,加上ToArray
    var charLocs = s.Select(c => plaintextAlphabet.IndexOf(c)).ToArray();
	
    // 回傳 s中各字元都存在plaintextalphabet字串中 且 charLocs為遞增
    // 此處檢查遞增就使用兩兩比對的方式
    return charLocs.All(x => x >= 0) && charLocs.Zip(charLocs.Skip(1), (pre,next) => pre < next).All(x => x);
}

在回覆中也有人提出了extend方法可以參考

參考

https://stackoverflow.com/questions/577590/pair-wise-iteration-in-c-sharp-or-sliding-window-enumerator

https://codesignal.com/