Wednesday, June 22, 2022
HomeWordPress DevelopmentTest if given Morse Code is legitimate

Test if given Morse Code is legitimate


View Dialogue

Enhance Article

Save Article

Like Article

Given a string S representing a Morse Code, the duty is to test is the code is legitimate or not. A Morse code is legitimate if that meets all of the under necessities:

  • Any message should start with a dot. [ ‘.’ ]
  • Any message should finish with a splash. [ ‘-‘ ]
  • Each dot should have a corresponding sprint after it to shut it.

Examples:

Enter: S = “.–“
Output: Vaild

Enter: S = “.”
Output: Invalid

Enter: S = “-“
Output: Invalid

 

Method: It is a easy implementation based mostly downside the place the primary, final and every pair of characters must be checked for the given situations. Observe the given steps to unravel the issue:

  • If the primary or final characters will not be dot and sprint respectively then the string is invalid.
  • Traverse the message from 0 to N-1:
    • If the character at index i is a dot however at index i+1 shouldn’t be a sprint (-), then the code is invalid.
  • If the loop ends, means the message has met all the necessities. So the code is legitimate.

Beneath is the implementation for the above strategy:

C++14

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

bool isValidMorse(string& code)

{

    int n = code.size();

  

    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 most important()

{

    string code = ".--";

  

    

    if (isValidMorse(code))

        cout << "Legitimate";

    else

        cout << "Invalid";

    return 0;

}

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments