I must write a program that will retrieve from the user the string consisting only letters "A" and "B". That string length is 10 characters (each character must be read separately). The program should detect and signal when it finds the sequence "ABBA" is in that string.
How to do it without arrays? I think the only way to do it, is make 10 scanf, and many of IF statements.
You can have 4 states: state 0 is looking for the first A, state 1 is looking for the first B, state 2 is looking for the second B, and state 3 is looking for the second A:
int state = 0;
for (int i = 0; i < 10; i ++) {
char c = getchar();
if (c == 'A' && (state == 0 || state == 3)) {
// found match, advance
state ++;
continue;
}
if (c == 'B' && (state == 1 || state == 2)) {
// found match, advance
state ++;
continue;
}
if (state == 4) {
// finished, we can break
break;
}
// no match, reset
state = 0;
}
if (state == 4) {
puts("substring found");
} else {
puts("substring not found");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.