[英]Java check if the string is an anagram of another string O ( log n )
因此,我最近一直在研究與算法的運行時復雜度有關的所有問題,並想學習如何在n的規模增加時進行更改以提高效率,所以本質上我的目標是學習如何制作事物O(日志n)。 對自己想,我知道這個小時我可以做一個很好的小項目,那就是創建一個字謎檢查器。
我翻遍了幾篇SO帖子,看到有人評論說,如果您將字母表中的每個字母都分配給一個數字,則可以將其設置為log n:
final Map<Character, Integer> map;
String str = "hello";
String check = "olleh";
map = new HashMap<>();
map.put('a', 2);
map.put('b', 3);
map.put('c', 4);
map.put('d', 7);
map.put('e', 11);
map.put('f', 13);
map.put('g', 17);
map.put('h', 19);
map.put('i', 23);
map.put('j', 29);
map.put('k', 31);
map.put('l', 37);
map.put('m', 41);
map.put('n', 43);
map.put('o', 47);
map.put('p', 53);
map.put('q', 59);
map.put('r', 61);
map.put('s', 67);
map.put('t', 71);
map.put('u', 73);
map.put('v', 79);
map.put('w', 83);
map.put('x', 89);
map.put('y', 97);
map.put('z', 101);
然后我創建了方法:
public static boolean isAnagram(String s, String check,Map<Character, Integer> map) {
int stringTotal = 0;
int checkTotal = 0;
for(char ch: s.toCharArray()){
int i = map.get(ch);
stringTotal += ch;
}
for(char ch: check.toCharArray()){
int i = map.get(ch);
checkTotal +=ch;
}
if (stringTotal == checkTotal){
return true;
}
return false;
}
我認為該方法是O(n ^ 2),因為它具有兩個獨立的循環,我無法想到將其創建為O(log n)方法的邏輯。
任何指針都很棒
看起來是O(2n)
:一個n
循環。 你會得到O(n^2)
如果你窩循環n
的循環中n
,就像這樣:
int count = 0;
for ( int x = 0; x < n; x++ )
for ( int y = 0; y < n; y++ )
count++;
在這里, count
將為n*n
或n 2 。
在您粘貼的代碼中,有兩個循環:
int count = 0;
for ( int x = 0; x < n; x++ )
count++;
for ( int y = 0; y < n; y++ )
count++;
此處, count
為n+n
或2n。
沒有辦法使O(log n)
函數,因為您將始終需要檢查所有n
值(所有字母)。
例如,讓我們說,我們計算出准確的時間復雜度的功能是log(n)
注意,這是從訂單不同O(log n)
與系數和低階方面確實走)。
現在,如果n = 10
; 然后log(n) = 2.3
(大約),如果僅查看2.3個字母,就不能確定十個字母的單詞是另一個10個字母的單詞的字謎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.