Java實現字符串的匹配
假設我們有一個一定個數的字母組成字串,我給每個字母分配一個素數,從2開始,往后類推。這樣A將會是2,B將會是3,C將會是5,等等。現在我遍歷第一個字串,把每個字母代表的素數相乘。你最終會得到一個很大的整數,對吧?
然后——輪詢第二個字符串,用每個字母除它。如果除的結果有余數,這說明有不匹配的字母。如果整個過程中沒有余數,你應該知道它是第一個字串恰好的子集了。
思路總結如下:
1.定義最小的26個素數分別與字符'A'到'Z'對應。
2.遍歷長字符串,求得每個字符對應素數的乘積。
3.遍歷短字符串,判斷乘積能否被短字符串中的字符對應的素數整除。
4.輸出結果。
至此,如上所述,上述算法的時間復雜度為O(m+n),時間復雜度最好的情況為O(n)
package contcurrentandalgorithm; /** * * @author Administrator * zyyjiao@mail.ustc.edu.cn */ public class SushuStringFind { public static void main(String[] args) { int primeNumber[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101}; String strOne = "ABCDEFGHLMNOPQRS"; String strTwo = "ABCDEFGHL"; // 這里需要用到大整數 int product = 1; //大整數除法的代碼,下頭給出。 // 遍歷長字符串,得到每個字符對應素數的乘積 for (int i = 0; i < strOne.length(); i++) { int index = strOne.charAt(i) - 'A'; product = product * primeNumber[index]; } // 遍歷短字符串 for (int j = 0; j < strTwo.length(); j++) { int index = strTwo.charAt(j) - 'A'; // 如果余數不為0,說明不包括短字串中的字符,跳出循環 if (product % primeNumber[index] != 0) { break; } if (strTwo.length() == j) //cout << "true" << endl; { System.out.println("true"); } else //cout << "false" << endl; { System.out.println("false"); } } } } |