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

21 May, 2021
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’ 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.Now, it is defined at the string must end with an ‘a’ to be accepted.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.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.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling.
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.Now, it is defined at the string must end with an ‘a’ to be accepted.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.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.Here, if it gets an ‘a’, it again enters the final state Q1 else for consecutive ‘b’s, it keeps circling.
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.
Now, it is defined at the string must end with an ‘a’ to be accepted.
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.
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.
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’ 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.Now, it is defined at the string must end with an ‘b’ to be accepted.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.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.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling.
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.Now, it is defined at the string must end with an ‘b’ to be accepted.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.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.Here, if it gets an ‘b’, it again enters the final state Q3 else for consecutive ‘a’s, it keeps circling.
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.
Now, it is defined at the string must end with an ‘b’ to be accepted.
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.
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.
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:  
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.List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol.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.Define all the state transitions using state function calls.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.
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.
List all the valid transitions. Here ‘a’ and ‘b’ are valid symbols. Each state must have a transition for every valid symbol.
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.
Define all the state transitions using state function calls.
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++
Java
Python3
C#
Javascript
// C++ Program for DFA that accepts string// if it starts and ends with same character #include <bits/stdc++.h>using namespace std; // States of DFAvoid q1(string, int);void q2(string, int);void q3(string, int);void q4(string, int); // Function for the state Q1void 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 Q2void 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 Q3void 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 Q4void 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 Q0void 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 Codeint main(){    string s = "abbaabb";     // Since q0 is the starting state    // Send the string to q0    q0(s, 0);}
// Java Program for DFA that accepts string// if it starts and ends with same characterclass 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 Program for DFA that accepts string# if it starts and ends with same character # Function for the state Q1def 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 Q2def 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 Q3def 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 Q4def 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 Q0def 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 Codeif __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# Program for DFA that accepts string// if it starts and ends with same characterusing 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
<script> // Javascript Program for DFA that accepts string// if it starts and ends with same character  // Function for the state Q1function 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 Q2function 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 Q3function 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 Q4function 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 Q0function 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 Codevar s = "abbaabb"; // Since q0 is the starting state// Send the string to q0q0(s, 0); // This code is contributed by importantly. </script>
No
 
Time Complexity: O(N) 
ankthon
Rajput-Ji
importantly
DFA
Pattern Searching
Strings
Theory of Computation & Automata
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if an URL is valid or not using Regular Expression
Search a Word in a 2D Grid of characters
Wildcard Pattern Matching
How to check if string contains only digits in Java
Check if a string contains uppercase, lowercase, special characters and numeric values
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4