w3resource

Java: Check whether a string is pq-balanced or not

Java String: Exercise-70 with Solution

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:

Java String Exercises: Check whether a string is pq-balanced or not

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:

Flowchart: Java String Exercises - Check whether a string is pq-balanced or not

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to return the substring that is between the first and last appearance of the substring 'toast' in the given string,or return the empty string if substirng 'toast' does not exists.
Next: Write a Java program to check two given strings whether any one of them appear at the end of the other string (ignore case sensitivity).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.