Compiler design practical file
Program :- the program in Java that verifies the s->as/bs/a pattern in compiler design with user input
Source code:- import java.util.Scanner;
public class PatternMatcher {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
if (isMatchingPattern(str)) {
System.out.println("The string matches the pattern.");
} else {
System.out.println("The string does not match the pattern.");
}
}
public static boolean isMatchingPattern(String str) {
int n = str.length();
if (n == 0) {
return false;
} else if (str.charAt(0) != 'a') {
return false;
}
int i = 1;
while (i < n && str.charAt(i) == 'a') {
i++;
}
if (i == n) {
return true;
} else if (str.charAt(i) == 'b') {
i++;
while (i < n && str.charAt(i) == 's') {
i++;
}
if (i == n || str.charAt(i) != 'a') {
return false;
}
i++;
while (i < n && str.charAt(i) == 's') {
i++;
}
if (i == n) {
return true;
} else {
return false;
}
} else if (str.charAt(i) == 'a') {
i++;
while (i < n && str.charAt(i) == 's') {
i++;
}
if (i == n) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
*******************************************
Program Java program that checks if a given string matches the pattern S -> a^n b^n c^n
Source code:- import java.util.Scanner;
public class StringPatternVerifier {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string to check: ");
String s = input.nextLine();
if (checkStringPattern(s)) {
System.out.println("The string matches the pattern.");
} else {
System.out.println("The string does not match the pattern.");
}
}
public static boolean checkStringPattern(String s) {
int aCount = 0;
int bCount = 0;
int cCount = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'a') {
aCount++;
} else if (c == 'b') {
bCount++;
} else if (c == 'c') {
cCount++;
} else {
// If there are any other characters in the string, it doesn't match the pattern.
return false;
}
// If b or c counts ever exceed a count, the string doesn't match the pattern.
if (bCount > aCount || cCount > aCount) {
return false;
}
}
// If all three counts are equal, the string matches the pattern.
return aCount == bCount && bCount == cCount;
}
}
Comments
Post a Comment