先輸入字典中單詞的個數,再輸入n個單詞作為字典單詞。輸入一個單詞,查找其在字典中兄弟單詞的個數再輸入數字n
輸出描述:
根據輸入,輸出查找到的兄弟單詞的個數
輸入例子:
3 abc bca cab abc 1輸出例子:
2 bca這個題目的問題描述讓人很是糊涂。正確的描述應該是這樣的:輸入描述:
先輸入字典中單詞的個數n,再輸入n個單詞作為字典單詞。
再輸入一個單詞,查找其在字典中兄弟單詞的個數m
再輸入數字k
輸出描述:
根據輸入,輸出查找到的兄弟單詞的個數m然后輸出查找到的兄弟單詞的第k個單詞。另外這題還有一個邊界條件判斷:輸入的兄弟單詞索引號k超過兄弟單詞總數時,只輸出兄弟單詞的總數這題自己走的最大的彎路是:開始沒有把判斷兄弟單詞寫成函數,在對broWord和vec_words[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;}
新聞熱點
疑難解答