ys memos

Blog

[Rust]leetcode 804 Unique Morse Code Words


leetcode

2022/04/23


入力された文字列の配列の各文字列をモールス信号に変換して結合した信号が,何種類あるのかを求める問題

今回は,Rust を用いて,シンプルな解法を作ってみた.


main.rs
use std::collections::HashSet;

const morse: &[&str] = &[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];

fn to_index(b: u8) -> usize {
  (b as usize) - 97
}

fn transform(word: String) -> String {
  let mut series = String::new();
  for b in word.bytes() {
    let i = to_index(b);
    series.push_str(&morse[i].to_string());
  }
  series
}

impl Solution {
  pub fn unique_morse_representations(words: Vec<String>) -> i32 {
    let mut set: HashSet<String> = HashSet::new();
    for word in words {
      let series = transform(word);
      set.insert(series);
    }
    set.len() as i32
  }
}


use std::collections::HashSet;

文字列→モールス信号への変換のためには,アルファベット・モールス符号対応表が必要となる.

これは,問題分で提示されているので,それをコピーしてきて,配列として準備する.

'a'の場合は0番目,'b'の場合は1番目といったように対応している.

const morse: &[&str] = &[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];

これは,morseの何番目を用いればよいのかを求めるために使う.

fn to_index(b: u8) -> usize {
  (b as usize) - 97
}

予め定義したmorseの,アルファベットの番号の信号を接続し,seriesを作成し,戻り値として返す.

fn transform(word: String) -> String {
  let mut series = String::new();
  for b in word.bytes() {
    let i = to_index(b);
    series.push_str(&morse[i].to_string());
  }
  series
}

ここで,モールス信号の種類をカウントするためのHashSetを初期化しておく.

impl Solution {
  pub fn unique_morse_representations(words: Vec<String>) -> i32 {
    let mut set: HashSet<String> = HashSet::new();

この際,重複の有無に関わらずHashSetのキーの有無としてカウントされるため,題意を満たす.

    for word in words {
      let series = transform(word);
      set.insert(series);
    }

    set.len() as i32
  }
}

Rust を勉強中のため,一問解くために(思考をコード化するために)リファレンスや StackOverflow 等を調べる必要があり,かなり時間がかかってしまう・・・

しかし,頭が活性化している感覚が楽しいですね 😄


関連タグを探す