算法与数据结构中,有时候需要先排序在做其他事情,这里总结一些比较有趣的题目,说明排序在解题过程中的重要性。
242. Valid Anagram [LeetCode]
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 类似于华为的兄弟单词那个题
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
查找兄弟单词
题目说明请看华为机试题查找兄弟单词。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
// 这里,不能传引用
bool isBrother(string a, string b){
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (a == b)return true;
return false;
}
void showBrother(const vector<string>& v){
cout << "------------ Brother words --------------" << endl;
for (auto str : v){
cout << str << endl;
}
}
int test(){
int n;
vector<string> word_dict;
vector<string> brother_word;
while (cin >> n){
word_dict.clear();
brother_word.clear();
string temp;
for (int i = 0; i < n; i++)
{
cin >> temp;
word_dict.push_back(temp);
}
string key_word;
int index;
cin >> key_word;
cin >> index;
// 查找是不是兄弟单词
for (int i = 0; i < word_dict.size(); i++)
if (key_word != word_dict[i] && isBrother(key_word, word_dict[i]))
brother_word.push_back(word_dict[i]);
sort(brother_word.begin(), brother_word.end());
cout << brother_word.size() << endl;
if (index <= brother_word.size())
cout << brother_word[index - 1] << endl;
showBrother(brother_word);
}
return EXIT_SUCCESS;
}
改试卷(美团点评)
请查看前面的博客,2017美团机试题目改试卷(美团点评)。
排序+对撞指针
请查看前面的博客,LeetCode经典问题3 SUM。
未完待续。。。