Leetcode: Anagrams(顛倒字母而成的字)


題目

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

 

思路

1. 使用數組模擬哈希表, 數組下標0-25分別代表字符'a'-'z', a[0] 代表 'a' 在單詞中出現的次數

2. 排序, 只有相鄰的單詞才有可能是相同的

3. 這么慢的方法沒想到 176ms 就能通過

 

總結

1. word 起初沒有對 char 數組初始化, 結果 VS 成功運行, 但 Leetcode 上卻是 WA. VS 真是寵壞一批程序員

 

代碼

class word {
public:
	word() {
		memset(chars, 0, sizeof(chars));
		index = 0;
	}
	int chars[26];
	int index;
	bool operator<(const word &ths) const {
		for(int i = 0; i < 26; i ++) {
			if(this->chars[i] != ths.chars[i]){
				return this->chars[i] < ths.chars[i];
			}
		}
		return this->index < ths.index;
	}
	bool operator==(const word &ths) const {
		for(int i = 0; i < 26; i ++) {
			if(this->chars[i] != ths.chars[i]) {
				return false;
			}
		}
		return true;
	}
};

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
		vector<word> record;
		for(int i = 0; i < strs.size(); i ++) {
			record.push_back(buildWord(strs[i], i));
		}
		sort(record.begin(), record.end());
		vector<word> res;
		bool flag = false;
		for(int i = 1; i < record.size(); i ++) {
			if(record[i] == record[i-1]) {
				if(!flag) {
					res.push_back(record[i-1]);
					res.push_back(record[i]);
					flag = true;
				}else{
					res.push_back(record[i]);
				}
			}else{
				flag = false;
			}
		}
		return decomposition(res, strs);
    }

	word buildWord(const string &str, const int &index) {
		word newword;
		for(int i = 0; i < str.size(); i ++) {
			newword.chars[str[i]-'a'] ++;
		}
		newword.index = index;
		return newword;
	}
	vector<string> decomposition(vector<word> &vec, vector<string> &strs) {
		vector<string> res;
		for(int i = 0; i < vec.size(); i++) {
			res.push_back(strs[vec[i].index]);
		}
		return res;
	}
};

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM