- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to check whether a given string is Heterogram or not
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
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");
To Continue Learning Please Login
Login with Google