[C#][LeetCode] 804. Unique Morse Code Words

這題要將英文轉換成摩斯密碼,並計算出重複字串的數量,我用 Linq 輕鬆解決。

public class Solution {
    
    public int UniqueMorseRepresentations(string[] words) {
        
        string[] morseCode = new string[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        
        List<char> listAToZ = Enumerable.Range('a', 26)
                                        .Select(x => (char)x)
                                        .ToList();
        
        var morseCodeAns = words.Select(x => 
        {
            var temp = x.Select(y => morseCode[listAToZ.IndexOf(y)]);            
            return string.Join(string.Empty, temp);
        });
        
        return morseCodeAns.Distinct().Count();
    }
}

 



這裡的資訊對您有用嗎?歡迎斗內給我