首頁 > Java > java教程 > Java 中的 Anagram 程式

Java 中的 Anagram 程式

PHPz
發布: 2024-08-30 16:26:59
原創
919 人瀏覽過

Anagram 是透過重新排列或重新排列不同單字的字母而形成的單字;字謎詞的要點是字母只能使用一次,並且不應在新單字中重複。 Anagram 是具有相同數量字母的單字。這裡的計數很重要。 Java中的Anagram程式可以透過對兩個字串進行排序和比較來按上述方式使用。如果這些成功,則表示字串是一個字謎。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

演算法:

讓我們來看看從特定單字取得字謎詞的演算法。字謎詞可以用三種方式找到。我們將一一解釋這三種方式。基本演算法包括檢查字串的長度。一旦長度相同,就可以對其進行排序或計數並檢查字謎。

Java 中的 Anagram 程式範例

對於給定的字串,我們可以做的第一件事就是對兩個要驗證的給定字串進行排序,以驗證它們是否是字謎詞。排序完成後,就可以依照排序後的順序進行比較。此方法的時間複雜度為O(n Logn)。 Java 程式碼可以寫成如下:

範例#1

代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

// JAVA program to validate if two strings are anagrams

import java.io.*;

import java.util.Arrays;

import java.util.Collections;

class Main {

/* Below is a function which checks if the strings are anagram */

static boolean checkAnagram(char[] strana1, char[] strana2)

{

// Finding lengths of strings

int len1 = strana1.length;

int len2 = strana2.length;

// If lengths do not match then they cannot be anagrams

if (len1 != len2)

return false;

// Sort both strings

Arrays.sort(strana1);

Arrays.sort(strana2);

// Comparing the strings which are sorted earlier

for (int i = 0; i < len1; i++)

if (strana1[i] != strana2[i])

return false;

return true;

}

/* Main program to test Anagram*/

public static void main (String args[])

{

char strana1[] = { 't', 'e', 's', 't' };

char strana2[] = { 't', 't', 'e', 'w' };

if (checkAnagram(strana1, strana2))

System.out.println("The strings to be checked are" + " anagram of each other");

else

System.out.println("The strings to be checked are not" + " anagram of each other");

}

}

登入後複製

上面的程式先檢查兩個給定字串的長度。如果字串的長度不同,則傳回 false。只有當兩個字串的長度相同時,程式才會繼續進行。透過使用數組排序功能,它將對兩個數組中的字串進行排序。一旦對兩個字串使用陣列排序函數,就會對字串進行比較,並在循環中比較每個字母。如果 for 迴圈成功且兩個字串中的所有字母都相同,則輸出將是一個字謎詞。即使有一個字母不匹配,也會回傳 false。這裡的主程式檢查字串並根據 checkAnagram 函數傳回的結果顯示字串是否是字謎詞。

輸出:

Java 中的 Anagram 程式

如果我們將輸入更改為“t”、“t”、“e”、“s”而不是 w,輸出將如下所示。

輸出:

Java 中的 Anagram 程式

範例#2

當驗證的字串較小時可以使用此方法。此方法考慮儲存的字元為8位,可能可儲存256個字元。在這個方法中,可以先使用大小為256的count數組對字串進行計數,並將count數組中所有需要的值初始化為0。遍歷該數組,並在遍歷的同時遞增count。完成此操作後,您可以比較計數數組。如果計數相同,則傳回結果為 true。

代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

import java.io.*;

import java.util.*;

class ANA {

static int NO_CHARS = 256;

/* Below is a function which checks if the strings are anagram */

static boolean isAnagram(char strana1[], char strana2[])

{

// Here we create two arrays and initialize it to 0

int cnt1[] = new int[NO_CHARS];

Arrays.fill(cnt1, 0);

int cnt2[] = new int[NO_CHARS];

Arrays.fill(cnt2, 0);

int i;

// For every character in input strings, increment the count

for (i = 0; i < strana1.length && i < strana2.length;

i++) {

cnt1[strana1[i]]++;

cnt2[strana2[i]]++;

}

// Checking If both strings are of different length

if (strana1.length != strana2.length)

return false;

// Compare count arrays

for (i = 0; i < NO_CHARS; i++)

if (cnt1[i] != cnt2[i])

return false;

return true;

}

/* Main program to test to check if string is Anagram or not*/

public static void main(String args[])

{

char strana1[] = ("silent").toCharArray();

char strana2[] = ("lisent").toCharArray();

if (isAnagram(strana1, strana2))

System.out.println("The strings to be checked are" + " anagram of each other");

else

System.out.println("The strings to be checked are not" + " anagram of each other");

}

}

登入後複製

輸出:

Java 中的 Anagram 程式

範例 #3

可以使用Java中的StringBuilder函數來檢查Anagram。我們可以使用 deletechartAt() 方法來刪除第二個字串中出現的任何字元。

代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

public class Main

{

static void findAnagram(String str1, String str2)

{

String copystr1 = str1.replaceAll( " ", "").toLowerCase();

String copystr2 = str2.replaceAll(" ", "").toLowerCase();

//Setting the initial status to true

boolean flag = true;

if(copystr1.length() != copystr2.length())

{

//If copystr1 and copystr2 do not have same length then set the flag to false

flag = false;

}

else

{

//changing copystr1 to char array

char[] str1Array = copystr1.toCharArray();

//Creating StringBuilder from copystr2

StringBuilder sb = new StringBuilder(copystr2);

//Validating if  each character of str1Array is present in string builder

for (char c : str1Array)

{

int index = sb.indexOf(""+c);

if (index != -1)

{

sb = sb.deleteCharAt(index);

}

else

{

//If each character is not present, setting flag to false and breaking the loop

flag = false;

break;

}

}

}

if(flag)

{

System.out.println(str1+" and "+str2+" are anagrams");

}

else

{

System.out.println(str1+" and "+str2+" are not anagrams");

}

}

public static void main(String[] args)

{

findAnagram("Silent", "Listen");

}

}

登入後複製

此處的程式使用該標誌並使用字串產生器模組來幫助刪除多餘的字元。

輸出:

Java 中的 Anagram 程式

以上是Java 中的 Anagram 程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
java可以做為web的後端嗎?
來自於 1970-01-01 08:00:00
0
0
0
安裝JAVA
來自於 1970-01-01 08:00:00
0
0
0
無法安裝java
來自於 1970-01-01 08:00:00
0
0
0
求救:JAVA加密的資料PHP解密
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板