


先輸入字典中單詞的個(gè)數(shù),再輸入n個(gè)單詞作為字典單詞。輸入一個(gè)單詞,查找其在字典中兄弟單詞的個(gè)數(shù)再輸入數(shù)字n
輸出描述:
根據(jù)輸入,輸出查找到的兄弟單詞的個(gè)數(shù)
輸入例子:
3 abc bca cab abc 1輸出例子:
2 bca這個(gè)題目的問題描述讓人很是糊涂。正確的描述應(yīng)該是這樣的:輸入描述:
先輸入字典中單詞的個(gè)數(shù)n,再輸入n個(gè)單詞作為字典單詞。
再輸入一個(gè)單詞,查找其在字典中兄弟單詞的個(gè)數(shù)m
再輸入數(shù)字k
輸出描述:
根據(jù)輸入,輸出查找到的兄弟單詞的個(gè)數(shù)m然后輸出查找到的兄弟單詞的第k個(gè)單詞。另外這題還有一個(gè)邊界條件判斷:輸入的兄弟單詞索引號k超過兄弟單詞總數(shù)時(shí),只輸出兄弟單詞的總數(shù)這題自己走的最大的彎路是:開始沒有把判斷兄弟單詞寫成函數(shù),在對broWord和vec_words[i]進(jìn)行排序比較時(shí)直接對原單詞進(jìn)行了操作,這樣導(dǎo)致結(jié)果不對,應(yīng)該采用中間變量緩存處理。寫成函數(shù)后,排序比較變成局部變量的處理,因此不會(huì)影響到源實(shí)參。
教訓(xùn):能封裝成函數(shù)的就寫成函數(shù)在內(nèi)部處理
完整AC后的代碼:
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;bool isBroWord(string word1,string word2){ if(word1==word2) return false; sort(word1.begin(),word1.end()); sort(word2.begin(),word2.end()); return word1==word2;}int main(){ int wordCnt; while(cin>>wordCnt){ int k; string word; vector<string> vec_words; string broWord; vector<string> vec_broWords; for(int i=0;i<wordCnt;i++){ cin>>word; vec_words.push_back(word); } //字典排序 sort(vec_words.begin(),vec_words.end()); cin>>broWord; for(int i=0;i<vec_words.size();i++){ if(isBroWord(broWord,vec_words[i])) vec_broWords.push_back(vec_words[i]); } cin>>k; cout<<vec_broWords.size()<<endl; if(vec_broWords.size()>=k)//邊界判斷 cout<<vec_broWords[k-1]<<endl; } return 0;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注