資源簡介
這是我的數據結構課程設計,采用了KMP算法和鍵樹算法統計單詞數量
代碼片段和文件信息
#include??
#include?
#include?
#include?
#include?
#define?N?3
//特征詞個數
#define?MAX?26
//字母種類
struct?TrieNode//樹的結點結構
{????
?int?Count;
?TrieNode?*Child[MAX];//指向兒子結點
?TrieNode()//每個結點的初始化
?{??
??Count=0;
??for?(int?i=0;i ?}
};
inline?unsigned?__int64?GetCycleCount()
{
__asm?_emit?0x0F
__asm?_emit?0x31
}
void?Format(char?*text)//把字符串中的大寫改寫成小寫,去掉標點符號
{
?int?i=0j;
?while(text[i])
?{???
??while(!isalpha(text[i])&&text[i])?
???for(j=i;text[j];j++)?text[j]=text[j+1];//去掉標點符號
??if(text[i]>=‘A‘&&text[i]<=‘Z‘)?text[i]=text[i]+‘a‘-‘A‘;//大寫改寫成小寫
??i++;
?}
?i=0;
}
int?WordNumber(char?*Article)
//統計文章總單詞數
{
?int?Num=0;
?char?text[20];
?ifstream?f(Articleios::in);
?if(!f)
?{?
??cout<<“Cannot?Open?File.“;?return?0;
?}
?while?(f>>text)?
?{
??Format(text);
??if?(text[0])?Num++;//計數器加1
?}
?f.close();
?return?Num;;
}
void?TrieInsert(TrieNode?*&rootchar?*word)//向以root為根結點的樹中插入串word
{
?TrieNode?*temp=root;
?int?i=0j=0;
?if(temp==NULL)?
?{
??temp=new?TrieNode();
??root=temp;
?}
?while(word[i])
?{
??j=word[i]-‘a‘;
??if?(!temp->Child[j])?temp->Child[j]=new?TrieNode();//如果不存在,建新結點
??i++;???????
??temp=temp->Child[j];
??if?(word[i]==‘\0‘)?temp->Count++;
?}
}
int?TrieSearch(TrieNode?*rootchar?*word)//查找
{
?TrieNode?*temp=root;
?int?i=0j=0ans;
?if(temp==NULL)?return?0;
?while(word[i])
?{
??j=word[i]-‘a‘;
??if?(!temp->Child[j])?return?0;
??i++;
??temp=temp->Child[j];
??if?(word[i]==‘\0‘)?ans=temp->Count;
?}
?return?ans;
}
void?Trie(TrieNode?*&rootchar?*Article)
{
?char?text[20];?//存放從小說文件讀取的一行字符串
?ifstream?f(Articleios::in);
?if?(!f)
?{?
??cout<<“Cannot?Open?File.“< ?}
?while?(f>>text)//如果還沒到小說文件末尾
?{
??Format(text);
??TrieInsert(roottext);
?}
?f.close();
?return;
}
void?GetNext(const?char?*T?int?*next)
//求模式串T的next函數值并存入數組next。?
{?
?int?j?=?0?k?=?-1;?
?next[0]?=?-1;?
?while?(T[j])?
?{?
??if?(k?==?-1?||?T[j]?==?T[k])?
??{?
???++j;?++k;?
???if?(T[j]!=T[k])?next[j]?=?k;?
???else?next[j]?=?next[k];?
??}//?if
??else?k?=?next[k];?
?}//?while
}//GetNext
int?KMP(const?char?*Textconst?char?*Pattern)?
//const?表示函數內部不會改變這個參數的值。
{?
?if(!Text?||?!Pattern?||?Pattern[0]==‘\0‘?||?Text[0]==‘\0‘)?return?-1;//空指針或空串,返回-1。
?int?len=0;?
?const?char?*?c=Pattern;?
?while(*c++)?++len;//字符串長度。
?int?*next=new?int[len+1];
?GetNext(Patternnext);//求Pattern的next函數值
?int?i=0j=0index=0;?
?while(Text[i]&&Pattern[j])?
?{?
??if(Text[i]==Pattern[j])?
??{?
???++i;//?繼續比較后繼字符
???++j;?
??}?
??else?
??{?
???index?+=?j-next[j];?
???if(next[j]!=-1)?j=next[j];//?模式串向右移動
???else?
???{?
????j=0;?
????++i;?
???}?
??}?
?}//while
?delete?[]next;
?if(!Pattern[j])?
?return?index;//?匹配成功
?else?return?-1;???????
}//KMP
int?KMPSearch(char?*Articlechar?*keys)?
//查找函數該函數是整個程序的重要部分,對于輸入的每一個
//要查找的關鍵字從小說文件中逐行讀取字符串查找
{
?char?text[20];?//存放從
- 上一篇:MFC寫的錄屏代碼,保存格式為AVI
- 下一篇:圖像內容識別縮放 源代碼 C++
評論
共有 條評論