之前有朋友面試筆試被考到了這個問題,挺好的面試題。
既然是ios面試題,肯定不能像c實現那樣,寫一大堆hashtable的結構體的**,可以用foundation物件喲
nsstring *str = @"aabbcdeffffadisldkfidjsdflksjdfie";
nsmutablearray *arr = [nsmutablearray array];
nsuinteger maxoccurence = 0;
unichar tempchr = 0;
[str enumeratesubstringsinrange:nsmakerange(0, [str length]) options:nsstringenumerationbycomposedcharactersequences usingblock:^(nsstring *substring, nsrange substringrange, nsrange enclosingrange, bool *stop) ];
nslog(@"%@, %@", [[[dictarray sortedarrayusingdescriptors:@[[nssortdescriptor sortdescriptorwithkey:@"count" ascending:no]]] objectatindex:0] objectforkey:@"object"], [[[dictarray sortedarrayusingdescriptors:@[[nssortdescriptor sortdescriptorwithkey:@"count" ascending:no]]] objectatindex:0] objectforkey:@"count"]); // 對陣列進行desc排序 取idx = 0的字典,然後取資料
nscountedset也可以統計單詞出現的次數。例如:
nsstring *str = @"you are damn right, you are damn good.";
nscountedset *set = [[nscountedset alloc] init];
[str enumeratesubstringsinrange:nsmakerange(0, [str length]) options:nsstringenumerationbywords | nsstringenumerationlocalized usingblock:^(nsstring * _nullable substring, nsrange substringrange, nsrange enclosingrange, bool * _nonnull stop) ' | sort -rn -k2
輸出:damn 2
are 2
you 1
right, 1
good. 1
you 1
跑題了。。腦子裡面老是有引申的意思。
如果用c去實現腫麼整?上面提到了hashtable,這個是沒問題的
typedef struct item item;
typedef struct hashtable hashtable;
實現以下方法:
void freehashtable(hashtable* ht);
hashtable* createhashtable(int size);
int genhash(hashtable *hashtable, int key);
void addtohashtable(hashtable* ht, item* item);
item* getitemfromhashtable(hashtable* ht, int key);
genhash其實是根據key,返回陣列的下標,下標的值就是hash。又跑題了。
通過遍歷字串中的字元,寫入hashtable, 已經存在的就+1,並且儲存當前出現的最大值,一遍之後就取得正確答案。
這個方法要實現乙個hashtable,還挺麻煩的。
後來我想,如果不考慮空間複雜度的話,其實字元是有ascii碼的,如果不考慮多位元組編碼的話,那也是有限的喲
#define asciisize 256
int arr[asciisize] = ;
unsigned int maxoccurence = 0;
char ret;
乙個for迴圈,加入陣列對應的ascii下標,並且儲存當前出現的最大值,一遍之後也出來了,很方便,使用陣列就搞定了。
for (int i = 0; i < strlen(str); ++i)
}好吧。乙個小演算法題引申了不少內容。
查詢字串中出現次數最多的字元
如下 include using namespace std typedef struct nodesnode 返回次數最多的字元節點,從大到小排阿node 0 c count最大 snode checkcount snode node,int len for int i 0 i len 1 i s...
查詢出字串中出現最多的字元及其出現的次數
已知乙個字串,編寫函式查詢出該字串中出現最多的字元及其出現的次數。輸入字串str,把str給str sort,對str sort中的字元排序,在str sort中統計每個字元出現的次數並比較輸出最多的 include includeint main 從str sort第二個字元開始,比較字元,是不是...
查詢出字串中出現最多的字元及其出現的次數
已知乙個字串,編寫函式查詢出該字串中出現最多的字元及其出現的次數。輸入字串str,把str給str sort,對str sort中的字元排序,在str sort中統計每個字元出現的次數並比較輸出最多的 include includeint main 從str sort第二個字元開始,比較字元,是不是...