Finite State Machine: Check Whether String Ends with ‘abb’ or not

import java.io.*;
class anstring
{
	public static void main(String args[])throws IOException
	{
		int q[][]={{1,0},{1,2},{1,3},{0,1}};
		String st;
		BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
		System.out.println("Enter string:");
		st=obj.readLine();
		
		int s=0;
		System.out.print("q"+s);
		
		for(int i=0; i<st.length();i++)
		{
			if (st.charAt(i)=='a')
			{
				s=q[s][0];
				System.out.print("->q"+s);
			}
			else if (st.charAt(i)=='b')
			{
				s=q[s][1];
				System.out.print("->q"+s);
			}
		}
		
		System.out.println();
		if (s==3)
		{
			System.out.println("String ends with 'abb'");
		}
		else
		{
			System.out.println("String do not ends with 'abb'");
		}
	}
}


/* Output

Enter string:

abbaaaabb
q0->q1->q2->q3->q0->q1->q1->q1->q2->q3

String ends with 'abb'

Enter string:

babababa
q0->q0->q1->q2->q1->q2->q1->q2->q1

String do not ends with 'abb'
*/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.