codewars (6 kyu) Decode the Morse code

一、题目简介

1. Description:

In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world.
The Morse code encodes every character as a sequence of “dots” and “dashes”. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·.

NOTE: Extra spaces before or after the code have no meaning and should be ignored.

Your task is to implement a function that would take the morse code as input and return a decoded human-readable string.

2. 个人理解

本题就是让我们实现一个莫斯密码的解密函数。
输入:string morseCode
输出:string plainText

二、代码分析

1. 代码实现

std::string decodeMorse(std::string morseCode) {
    
    morseCode.erase(0, morseCode.find_first_not_of(" "));
    morseCode.erase(morseCode.find_last_not_of(" ") + 1);
    
    // ToDo: Accept dots, dashes and spaces, return human-readable message
    std::string decoded;
    
    std::string letter_digit = "";
    std::string space = "";
    
    int flag; // =0, letter change; =1,space change
    int old_flag = 1;
    
    //bool isFrontSpaces = true;  //currently detectd space is or is not extra spaces before the morse code
    
    for(auto p : morseCode)
    {
      if( p == '.' || p == '-')
      {
        letter_digit += p;
        flag = 0;
        //sFrontSpaces = false;  //when detec a dot or dash, set it to false
      }
      else if( p == ' ')
      {
        space += p;
        flag = 1;
      }
        
      if(old_flag != flag)
      {
        if(old_flag == 0)
        {
          decoded += MORSE_CODE[ letter_digit ];
          letter_digit = "";
        }
        else if(old_flag == 1 /* && !isFrontSpaces */)
        {
          if( space == "   " )
            decoded += " ";
          space = "";
        }
      }
        
      old_flag = flag;
    }
    
    if(flag == 0)
      decoded += MORSE_CODE[ letter_digit ];
      
    return decoded;
}

2. 实现思路

设置两个缓存器 letter_digit、space
       letter_digit:缓存收到的单词(Words)
       space:缓存收到的空格

设置两个标记位flag、old_flag
       flag:当前改变的是 letter_digit 还是 space
       old_flag:记录前一步的 flag

然后,逐字符的读取 morseCode ,利用 flag 和 old_flag 控制输出字母数字还是空格。

补充:看别人有用正则表达式进行匹配的。

link: Best Solutions

3. 收获

(1)C++去除字符串首部尾部的空格
(2)C++中,双引号 “a” 是 const char * 类型的。所以,进行比较时,需要使用单引号 'a’


永远别停下朝向更好的脚步!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值