Java program to check whether a given string is Heterogram or not

Java 8Object Oriented ProgrammingProgramming

A string is a Heterogram if no letter of the alphabet occurs more than once in it. An example of this is given as follows −

String = the big dwarf only jumps

This string is a Heterogram as each alphabet in the string occurred only once.

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main (String[] args) {
      String str = "mango";
      int n = str.length();
      int alphaList[] = new int[26];
      int flag = 1;
      System.out.println("The string is: " + str);
      for (int i = 0; i < n; i++) {
         if (str.charAt(i) != ' ') {
            if (alphaList[str.charAt(i) - 'a'] == 0) {
               alphaList[str.charAt(i) - 'a'] = 1;
         }else {
            flag = 0;
            break;
         }
      }
   }
   if(flag == 1)
      System.out.println("The above string is a Heterogram");
   else
      System.out.println("The above string is not a Heterogram");
   }
}

Output

The string is: mango
The above string is a Heterogram

Now let us understand the above program.

First, the string is displayed. Then a for loop is used to check if the string is a heterogram or not. For each alphabet of the string, its corresponding position in alphaList[] is updated to 1 if it occurs the first time. If the same alphabet occurs the second time then flag is set to 0 is break is used to exit the loop. The code snippet that demonstrates this is given as follows.

System.out.println("The string is: " + str);
for (int i = 0; i < n; i++) {
   if (str.charAt(i) != ' ') {
      if (alphaList[str.charAt(i) - 'a'] == 0) {
         alphaList[str.charAt(i) - 'a'] = 1;
      }else {
         flag = 0;
         break;
      }
   }
}

If flag is 1, then string is Heterogram and that is displayed. If flag is 0, then string is not Heterogram and that is displayed. The code snippet that demonstrates this is given as follows.

if(flag == 1)
System.out.println("The above string is a Heterogram");
else
System.out.println("The above string is not a Heterogram");
raja
Published on 06-Dec-2018 11:48:35
Advertisements