Check if given Morse Code is valid

View Discussion

Improve Article

Save Article

Like Article

Given a string S representing a Morse Code, the task is to check is the code is valid or not. A Morse code is valid if that meets all the below requirements:

  • Any message must begin with a dot. [ ‘.’ ]
  • Any message must end with a dash. [ ‘-‘ ]
  • Every dot must have a corresponding dash after it to close it.

Examples:

Input: S = “.–“
Output: Vaild

Input: S = “.”
Output: Invalid

Input: S = “-“
Output: Invalid

Approach: This is a simple implementation based problem where the first, last and each pair of characters need to be checked for the given conditions. Follow the given steps to solve the problem:

  • If the first or last characters are not dot and dash respectively then the string is invalid.
  • Traverse the message from 0 to N-1:
    • If the character at index i is a dot but at index i+1 is not a dash (-), then the code is invalid.
  • If the loop ends, means the message has met all the requirements. So the code is valid.

Below is the implementation for the above approach:

C++14

  

#include <bits/stdc++.h>

using namespace std;

  

bool isValidMorse(string& code)

{

    int n = code.length();

  

    if (code[0] != '.' || code[n - 1] != '-')

        return 0;

  

    for (int i = 0; i < n - 1; i++) {

        if (code[i] == '.' && code[i + 1] != '-')

            return 0;

    }

  

    return 1;

}

  

int main()

{

    string code = ".--";

  

    

    if (isValidMorse(code))

        cout << "Valid";

    else

        cout << "Invalid";

    return 0;

}

Output

Valid

Time Complexity: O(N)
Auxiliary Space: O(1)