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");
廣告