Java: Check whether a string is pq-balanced or not
70. Check PQ-Balance
Write a Java program that checks if a string has pq-balance if it contains at least one 'q' directly after each ‘p’. But a 'q' before the 'p' invalidates pq-balance.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to check if the string is pq-balanced
public boolean pqBalanceString(String stng) {
Boolean p = false; // Initialize flag for 'p'
Boolean q = false; // Initialize flag for 'q'
int len = stng.length(); // Get the length of the input string
// Iterate through the characters of the input string
for (int i = 0; i < len; i++) {
// Check if the current character is 'p' and 'q' flag is true, set 'p' flag to true and 'q' flag to false
if (stng.charAt(i) == 'p' && q == true) {
p = true;
q = false;
} else if (stng.charAt(i) == 'p') {
p = true;
}
// Check if the current character is 'q' and 'p' flag is true, set 'q' flag to true
if (stng.charAt(i) == 'q' && p == true)
q = true;
}
// If 'p' flag is false, set 'q' flag to true
if (p == false)
q = true;
return q; // Return the 'q' flag indicating pq-balance
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
String str1 = "gfpmpnppqab"; // Input string
// Display the given string and whether it is pq-balanced using pqBalanceString method
System.out.println("The given strings is: " + str1);
System.out.println("The string is pq-balanced? " + m.pqBalanceString(str1));
}
}
Sample Output:
The given strings is: gfpmpnppqab The string is pq-balanced? true The given strings is: gfpmpnpqpab The string is pq-balanced? false
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to verify that every 'p' in a string is immediately followed by a 'q' and flag any violation.
- Write a Java program to check pq-balance in a string by scanning character pairs sequentially.
- Write a Java program to determine whether every 'p' has a succeeding 'q' and no 'q' precedes any 'p'.
- Write a Java program to validate pq-balance using regular expressions to exclusively match "pq" patterns.
Go to:
PREV : Substring Between Two 'toast'.
NEXT : One String at End of Other.
Java Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.