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: VaildInput: S = “.”
Output: InvalidInput: 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
|
Valid
Time Complexity: O(N)
Auxiliary Space: O(1)