• 唯一摩尔斯密码


      国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。

      为了方便,所有26个英文字母对应摩尔斯密码表如下:

        [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
      给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。

    返回我们可以获得所有词不同单词翻译的数量。

    例如:
      输入: words = ["gin", "zen", "gig", "msg"]
      输出: 2
      解释:
      各单词翻译如下:
      "gin" -> "--...-."
      "zen" -> "--...-."
      "gig" -> "--...--."
      "msg" -> "--...--."

    共有 2 种不同翻译, "--...-." 和 "--...--.".

     

    思路:

      我们将数组 word 中的每个单词转换为摩尔斯码,并加入哈希集合(HashSet)中,最终的答案即为哈希集合中元素的个数。

    #include<iostream>
    #include<set>
    #include<vector>
    using namespace std;
    string map[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",
    ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--",
    "-..-","-.--","--.."} ;
    int uniqueMorseRepresentations(vector<string>& words) {
            set< string > st ;
            int len=words.size(),wordlen;
            for (int i=0;i<len;i++ )
            {
                string str,s ;
                s=words[i];
                wordlen=words[i].length();
                char c;
                //翻译每个单词,结果由str保存
                for (int j=0;j<wordlen;j++ )
                {
                    c = words[i][j];
                    str += map[ c - 'a' ] ;
                }
                st.insert( str ) ;
            }
    
            return st.size() ;
        }
    int main(){
        vector<string>words;
        string str;
        while (cin>>str)
        {
            words.push_back(str);
        }
        cout<<uniqueMorseRepresentations(words); 
        
    
    }

     

    因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/12806187.html

  • 相关阅读:
    IOS整体代码复习一
    IOS复习UIActionSheet&UIAlertView
    IOS复习Plist文件的读取和写入
    IOS复习UITextfield&UILabel
    iOS中判断两个圆是否重叠
    iOS指针回调函数
    ios函数指针
    iOS分区
    ios指针第二天
    iOS指针第一天
  • 原文地址:https://www.cnblogs.com/BlairGrowing/p/12806187.html
Copyright © 2020-2023  润新知