Open In App

Program to build a DFA to accept strings that start and end with same character

Last Updated : 15 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string consisting of characters a and b, check if the string starts and ends with the same character or not. If it does, print ‘Yes’ else print ‘No’.
Examples: 
 

Input: str = “abbaaba” 
Output: Yes 
Explanation: 
The given input string starts and ends with same character ‘a’ 
So the states of the below DFA Machine will be q0->q1->q2->q2->q1->q1->q2->q1 and q1 is a final state, 
Hence the output will be Yes.
Input: str = “ababab” 
Output: No 
Explanation: 
The given input string starts and ends with different character ‘a’ and ‘b’, 
So the states of the below DFA Machine will be q0->q1->q2->q1->q2->q1->q2 and q2 is not a final state, 
Hence the output will be No. 
 

 

Approach: 
DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.
In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {a, b}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state.
DFA Machine that accepts all strings that start and end with same character 
For the above problem statement, we must first build a DFA machine. DFA machine is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q1 and Q3 are the final states:
 

How does this DFA Machine works: 
The working of the machine depends on whether the first character is ‘a’ or ‘b’. 
 

  • Case 1: String starts with ‘a’ 
    1. Suppose the first character in the input string is ‘a’, then on reading ‘a’, the control will shift to the upper branch of the machine.
    2. Now, it is defined at the string must end with an ‘a’ to be accepted.
    3. At state Q1, if again ‘a’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.
    4. If it gets a ‘b’, then it has to leave the final state since a string ending in ‘b’ is not acceptable. So it moves to state Q2.
    5. Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling.
  • Case 2: String starts with ‘b’ 
    1. Suppose the first character in the input string is ‘b’, then on reading ‘b’, the control will shift to the upper branch of the machine.
    2. Now, it is defined at the string must end with an ‘b’ to be accepted.
    3. At state Q3, if again ‘b’ comes, it keeps circling at the same state because for the machine the last read character might be the last character of the string.
    4. If it gets a ‘a’, then it has to leave the final state since a string ending in ‘a’ is not acceptable. So it moves to state Q4.
    5. Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling.

Approach for designing the DFA machine: 
 

  1. Define the minimum number of states required to make the state diagram. Here Q0, Q1, Q2, Q3, Q4 are the defined states. Use functions for various states.
  2. List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol.
  3. Define the final states by applying the base condition. Q1 and Q3 are defined as the final state. If the string input ends at any of these states, it is accepted else rejected.
  4. Define all the state transitions using state function calls.
  5. Define a returning condition for the end of the string. If by following the process, the program reaches the end of the string, the output is made according to the state the program is at.

Below is the implementation of the above approach.
 

C++




// C++ Program for DFA that accepts string
// if it starts and ends with same character
 
#include <bits/stdc++.h>
using namespace std;
 
// States of DFA
void q1(string, int);
void q2(string, int);
void q3(string, int);
void q4(string, int);
 
// Function for the state Q1
void q1(string s, int i)
{
 
    // Condition to check end of string
    if (i == s.length()) {
        cout << "Yes \n";
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q2
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q2(s, i + 1);
}
 
// Function for the state Q2
void q2(string s, int i)
{
    // Condition to check end of string
    if (i == s.length()) {
        cout << "No \n";
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q2
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q2(s, i + 1);
}
 
// Function for the state Q3
void q3(string s, int i)
{
    // Condition to check end of string
    if (i == s.length()) {
        cout << "Yes \n";
        return;
    }
 
    // State transitions
    // 'a' takes to q4, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q4(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Function for the state Q4
void q4(string s, int i)
{
    // Condition to check end of string
    if (i == s.length()) {
        cout << "No \n";
        return;
    }
 
    // State transitions
    // 'a' takes to q4, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q4(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Function for the state Q0
void q0(string s, int i)
{
 
    // Condition to check end of string
    if (i == s.length()) {
        cout << "No \n";
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Driver Code
int main()
{
    string s = "abbaabb";
 
    // Since q0 is the starting state
    // Send the string to q0
    q0(s, 0);
}


Java




// Java Program for DFA that accepts string
// if it starts and ends with same character
import java.io.*;
public class GFG
{
     
    // Function for the state Q1
    static void q1(String s, int i)
    {
     
        // Condition to check end of string
        if (i == s.length())
        {
            System.out.println("Yes");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q2
        if (s.charAt(i) == 'a')
            q1(s, i + 1);
        else
            q2(s, i + 1);
    }
     
    // Function for the state Q2
    static void q2(String s, int i)
    {
        // Condition to check end of string
        if (i == s.length())
        {
            System.out.println("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q2
        if (s.charAt(i) == 'a')
            q1(s, i + 1);
        else
            q2(s, i + 1);
    }
     
    // Function for the state Q3
    static void q3(String s, int i)
    {
        // Condition to check end of string
        if (i == s.length())
        {
            System.out.println("Yes");
            return;
        }
     
        // State transitions
        // 'a' takes to q4, and
        // 'b' takes to q3
        if (s.charAt(i) == 'a')
            q4(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Function for the state Q4
    static void q4(String s, int i)
    {
        // Condition to check end of string
        if (i == s.length())
        {
            System.out.println("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q4, and
        // 'b' takes to q3
        if (s.charAt(i) == 'a')
            q4(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Function for the state Q0
    static void q0(String s, int i)
    {
     
        // Condition to check end of string
        if (i == s.length())
        {
            System.out.println("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q3
        if (s.charAt(i) == 'a')
            q1(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        String s = "abbaabb";
     
        // Since q0 is the starting state
        // Send the string to q0
        q0(s, 0);
    }
}
 
// This code is contributed by AnkitRai01


Python3




# Python3 Program for DFA that accepts string
# if it starts and ends with same character
 
# Function for the state Q1
def q1(s, i):
 
    # Condition to check end of string
    if (i == len(s)):
        print("Yes");
        return;
     
    # State transitions
    # 'a' takes to q1, and
    # 'b' takes to q2
    if (s[i] == 'a'):
        q1(s, i + 1);
    else:
        q2(s, i + 1);
 
# Function for the state Q2
def q2(s, i):
     
    # Condition to check end of string
    if (i == len(s)):
        print("No");
        return;
     
    # State transitions
    # 'a' takes to q1, and
    # 'b' takes to q2
    if (s[i] == 'a'):
        q1(s, i + 1);
    else:
        q2(s, i + 1);
 
# Function for the state Q3
def q3(s, i):
     
    # Condition to check end of string
    if (i == len(s)):
        print("Yes");
        return;
     
    # State transitions
    # 'a' takes to q4, and
    # 'b' takes to q3
    if (s[i] == 'a'):
        q4(s, i + 1);
    else:
        q3(s, i + 1);
 
# Function for the state Q4
def q4(s, i):
     
    # Condition to check end of string
    if (i == s.length()):
        print("No");
        return;
     
    # State transitions
    # 'a' takes to q4, and
    # 'b' takes to q3
    if (s[i] == 'a'):
        q4(s, i + 1);
    else:
        q3(s, i + 1);
 
# Function for the state Q0
def q0(s, i):
 
    # Condition to check end of string
    if (i == len(s)):
        print("No");
        return;
     
    # State transitions
    # 'a' takes to q1, and
    # 'b' takes to q3
    if (s[i] == 'a'):
        q1(s, i + 1);
    else:
        q3(s, i + 1);
 
# Driver Code
if __name__ == '__main__':
    s = "abbaabb";
 
    # Since q0 is the starting state
    # Send the string to q0
    q0(s, 0);
     
# This code is contributed by Rajput-Ji


C#




// C# Program for DFA that accepts string
// if it starts and ends with same character
using System;
 
class GFG
{
     
    // Function for the state Q1
    static void q1(string s, int i)
    {
     
        // Condition to check end of string
        if (i == s.Length)
        {
            Console.WriteLine("Yes");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q2
        if (s[i] == 'a')
            q1(s, i + 1);
        else
            q2(s, i + 1);
    }
     
    // Function for the state Q2
    static void q2(string s, int i)
    {
        // Condition to check end of string
        if (i == s.Length)
        {
            Console.WriteLine("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q2
        if (s[i] == 'a')
            q1(s, i + 1);
        else
            q2(s, i + 1);
    }
     
    // Function for the state Q3
    static void q3(string s, int i)
    {
        // Condition to check end of string
        if (i == s.Length)
        {
            Console.WriteLine("Yes");
            return;
        }
     
        // State transitions
        // 'a' takes to q4, and
        // 'b' takes to q3
        if (s[i] == 'a')
            q4(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Function for the state Q4
    static void q4(string s, int i)
    {
        // Condition to check end of string
        if (i == s.Length)
        {
            Console.WriteLine("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q4, and
        // 'b' takes to q3
        if (s[i] == 'a')
            q4(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Function for the state Q0
    static void q0(string s, int i)
    {
     
        // Condition to check end of string
        if (i == s.Length)
        {
            Console.WriteLine("No");
            return;
        }
     
        // State transitions
        // 'a' takes to q1, and
        // 'b' takes to q3
        if (s[i] == 'a')
            q1(s, i + 1);
        else
            q3(s, i + 1);
    }
     
    // Driver Code
    public static void Main ()
    {
        string s = "abbaabb";
     
        // Since q0 is the starting state
        // Send the string to q0
        q0(s, 0);
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript Program for DFA that accepts string
// if it starts and ends with same character
 
 
// Function for the state Q1
function q1( s, i)
{
 
    // Condition to check end of string
    if (i == s.length) {
        document.write( "Yes<br>");
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q2
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q2(s, i + 1);
}
 
// Function for the state Q2
function q2( s,  i)
{
    // Condition to check end of string
    if (i == s.length) {
        document.write( "No");
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q2
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q2(s, i + 1);
}
 
// Function for the state Q3
function q3( s,  i)
{
    // Condition to check end of string
    if (i == s.length) {
        document.write( "Yes");
        return;
    }
 
    // State transitions
    // 'a' takes to q4, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q4(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Function for the state Q4
function q4( s,  i)
{
    // Condition to check end of string
    if (i == s.length) {
        document.write( "No");
        return;
    }
 
    // State transitions
    // 'a' takes to q4, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q4(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Function for the state Q0
function q0( s,  i)
{
 
    // Condition to check end of string
    if (i == s.length) {
        document.write( "No");
        return;
    }
 
    // State transitions
    // 'a' takes to q1, and
    // 'b' takes to q3
    if (s[i] == 'a')
        q1(s, i + 1);
    else
        q3(s, i + 1);
}
 
// Driver Code
var s = "abbaabb";
 
// Since q0 is the starting state
// Send the string to q0
q0(s, 0);
 
// This code is contributed by importantly.
 
</script>


Output: 

No

 

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads