資料結構和演算法(字串)

2021-09-24 20:16:16 字數 1554 閱讀 1715

字串定義:由零個或多個字元組成的有限序列

字串的比較:一般只比較是否相等(可比大小,比相同位置上的字元的ascii值)

字串的儲存結構:

順序儲存:陣列

鏈式儲存:鍊錶

bf演算法:brute force,樸素的模式匹配演算法

核心思想:

有兩個字串s和t,長度為n和m。首先s[1]和t[1]比較,若相等,則再比較s[2]和t[2],一直到t[m]

為止;若s[1]和t[1]不等,則t向右移動乙個字元的位置,再依次進行比較

bf演算法例項:

#include #include void bruteforce(char mstr, char str)

j = 0;

while( '\0' != str[j] )

else

else

}if( count == len )

if( '\0' == mstr[i] && count != len )

}}void print(char str)

}}int main(void)

printf("\nplease enter the string (within 10) and enter # to end:\n");

fflush(stdin);

scanf("%c", &c);

while( '#' != c )

printf("\n");

//print(mstr);

//print(str);

bruteforce(mstr, str);

return 0;

}

kmp演算法:

#include #include #define maxbuffer 30

typedef struct string

str;

//i:字首

//j:字尾

void get_next(str t, int *next)

else

}else

}}int index_kmp(str t, str s) //返回子串t在主串s第pos個字元之後的位置

else

}if(j > t.len)

else

}int main(void)

s.str[0] = ' ';

i = 1;

printf("please enter the string of t, and enter # to end:\n");

fflush(stdin); //清除快取換行鍵

scanf("%c", &c);

while( '#' != c )

t.str[0] = ' ';

pos = index_kmp(t, s);

printf("the start of the substring is at the %d th position of the main string\n", pos);

return 0;

}

資料結構和演算法 字串

想要研究字串的資料結構和演算法,可以先看一遍字串自帶的一些的屬性和方法 557.反轉字串中的單詞 iii 給定乙個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。示例 輸入 let s take leetcode contest 輸出 s tel ekat edocteel...

資料結構與演算法 字串

判斷乙個串是不是回文串,往往要分開編寫,造成 的拖沓 int longestpalindrome const char s,int n return max void longestpalindrome test 上面的迴圈中,對於回文長度本身的奇偶性,我們進行區別處理。這樣有點拖沓。我們根據乙個簡...

資料結構與演算法 字串

生成n對括號的所有合法排列 描述 給定乙個非負整數n,生成n對括號的所有合法排列。解答 該問題解的個數就是卡特蘭數,但是現在不是求個數,而是要將所有合法的括號排列列印出來。該問題和 程式設計之美 的買票找零問題一樣,通過買票找零問題我們可以知道,針對乙個長度為2n的合法排列,第1到2n個位置都滿足如...