Java 程序检查给定字符串是否为异序词
如果字符串中没有字母出现超过一次,则该字符串是异序词。示例如下:
String = the big dwarf only jumps
这个字符串是异序词,因为字符串中的每个字母只出现一次。
演示此功能的程序如下所示。
示例
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");
}
}输出
The string is: mango The above string is a Heterogram
现在让我们了解上述程序。
首先,显示字符串。然后使用 for 循环检查字符串是否为异序词。对于字符串的每个字母,如果它第一次出现,则将其在 alphaList[] 中的相应位置更新为 1。如果相同的字母第二次出现,则将标志设置为 0,并使用 break 退出循环。演示此功能的代码片段如下所示。
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;
}
}
}如果标志为 1,则字符串为异序词,并显示出来。如果标志为 0,则字符串不是异序词,并显示出来。演示此功能的代码片段如下所示。
if(flag == 1)
System.out.println("The above string is a Heterogram");
else
System.out.println("The above string is not a Heterogram");
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP