The Wayback Machine - https://web.archive.org/web/20240804080107/https://www.geeksforgeeks.org/check-if-given-morse-code-is-valid/
Open In App

Check if given Morse Code is valid

Last Updated : 18 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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: Valid

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




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if
// the Morse code is valid or not
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;
}
 
// Driver's code
int main()
{
    string code = ".--";
 
    // Function Call
    if (isValidMorse(code))
        cout << "Valid";
    else
        cout << "Invalid";
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  // Java code to implement the approach
 
  // Function to find if
  // the Morse code is valid or not
  static boolean isValidMorse(String code)
  {
    int n = code.length();
 
    if (code.charAt(0) != '.' || code.charAt(n - 1) != '-')
      return false;
 
    for (int i = 0; i < n - 1; i++) {
      if (code.charAt(i) == '.' && code.charAt(i + 1) != '-')
        return false;
    }
 
    return true;
  }
 
 
  /* Driver program to test above function*/
  public static void main(String args[])
  {
    String code = ".--";
 
    // Function Call
    if (isValidMorse(code))
      System.out.println("Valid");
    else
      System.out.println("Invalid");
  }
}
 
// This code is contributed by shinjanpatra.


Python3




# Python3 code to implement the approach
 
# Function to find if
# the Morse code is valid or not
def isValidMorse(code):
 
    n = len(code)
 
    if (code[0] != '.' or code[n - 1] != '-'):
        return 0
 
    for i in range(n-1):
        if (code[i] == '.' and code[i + 1] != '-'):
            return 0
 
    return 1
 
# Driver's code
 
code = ".--"
 
# Function Call
if (isValidMorse(code)):
    print("Valid")
else:
    print("Invalid")
 
# This code is contributed by shinjanpatra


C#




/*package whatever //do not write package name here */
using System;
 
public class GFG
{
 
  // C# code to implement the approach
 
  // Function to find if
  // the Morse code is valid or not
  static bool isValidMorse(String code)
  {
    int n = code.Length;
 
    if (code[0] != '.' || code[(n - 1)] != '-')
      return false;
 
    for (int i = 0; i < n - 1; i++) {
      if (code[i] == '.' && code[(i + 1)] != '-')
        return false;
    }
 
    return true;
  }
 
 
  /* Driver program to test above function*/
  public static void Main(String []args)
  {
    String code = ".--";
 
    // Function Call
    if (isValidMorse(code))
      Console.WriteLine("Valid");
    else
      Console.WriteLine("Invalid");
  }
}
 
// This code contributed by shikhasingrajput


Javascript




<script>
       // JavaScript code for the above approach
 
 
       // Function to find if
       // the Morse code is valid or not
       function isValidMorse(code) {
           let n = code.length;
 
           if (code[0] != '.' || code[n - 1] != '-')
               return 0;
 
           for (let i = 0; i < n - 1; i++) {
               if (code[i] == '.' && code[i + 1] != '-')
                   return 0;
           }
 
           return 1;
       }
 
       // Driver's code
 
       let code = ".--";
 
       // Function Call
       if (isValidMorse(code))
           document.write("Valid");
       else
           document.write("Invalid");
 
   // This code is contributed by Potta Lokesh
   </script>


Output

Valid

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



Similar Reads

Morse Code Implementation
Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph. The algorithm is very simple. Every character in the English language is substituted by
9 min read
Count distinct strings possible by replacing each character by its Morse code
Given an array of strings arr[], the task is to count the number of distinct strings that can be generated from the given array by replacing each character of the strings by its Morse code. Below is the Morse code of all the lowercase alphabets: Examples: Input: arr[] = {"gig", "zeg", "gin", "msn"}Output: 2Explanation: Replacing each character of t
10 min read
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
Check if a given string is a valid Hexadecimal Color Code or not
Given a string str, the task is to check whether the given string is an HTML Hex Color Code or not. Print Yes if it is, otherwise print No. Examples: Input: str = “#1AFFa1”Output: Yes Input: str = “#F00”Output: Yes Input: str = ïŋ―”Output: No Approach: An HTML Hex Color Code follows the below-mentioned set of rules: It starts with the ‘#’ symbol.Then
7 min read
Check if the given RGB color code is valid or not
Given three numbers R, G and B as the color code for Red, Green and Blue respectively as in the form of RGB color code. The task is to know whether the given color code is valid or not. RGB Format: The RGB(Red, Green, Blue) format is used to define the color of an HTML element by specifying the R, G, B values range between 0 to 255. For example: RG
10 min read
Thue-Morse sequence
Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is an infinite binary sequence of 0s and 1s. The sequence is obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained so far. First few steps : Start with 0 Append complement of 0, we get 01 Append complement of 01, we get 0110 Append complement of 01
6 min read
Find first K characters in Nth term of the Thue-Morse sequence
Given two integers N and K, the task is to print the first K bits of the Nth term of the Thue-Morse sequence. The Thue-Morse sequence is a binary sequence. It starts with a "0" as its first term. And then after the next term is generated by replacing "0" with "01" and "1" with "10". Examples: Input: N = 3, K = 2Output: 01Explanation: The 1st term i
6 min read
Check if the given permutation is a valid BFS of a given Tree
Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 - 2 1 - 5 2 - 3 2 - 4 5 -
10 min read
Check whether triangle is valid or not if sides are given
Given three sides, check whether triangle is valid or not. Examples: Input : a = 7, b = 10, c = 5 Output : Valid Input : a = 1 b = 10 c = 12 Output : Invalid Approach: A triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met. 1.a + b &gt; c 2.a + c &gt; b 3.b + c
4 min read
Check if the given permutation is a valid DFS of graph
Given a graph with N nodes numbered from 1 to N and M edges and an array of numbers from 1 to N. Check if it is possible to obtain any permutation of array by applying DFS (Depth First Traversal) on given graph. Prerequisites: DFS | Map in CPP Examples: Input: N = 3, M = 2 Edges are: 1) 1-2 2) 2-3 P = {1, 2, 3} Output: YES Explanation: Since there
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg