# \#500 Keyboard Row
## *給定字串陣列words, 回傳該陣列中, 該字串都位於鍵盤上的同一行的字串(陣列型態)*
## Log
- build 20210926 by syhuang
## Set差集解
- 把鍵盤三行字串和input轉為Set做差集比較
- 只要其中一行的差集為空集合, 就表示該字串的字都在那一行
- javascript"空集合"用Array.length=0來做判斷
- leetcode submit runtime 91%, memory 5%
```javascript=
Set.prototype.difference = function(setB) {
var difference = new Set(this);
for (var elem of setB) {
difference.delete(elem);
}
return difference;
}
var findWords = function(words) {
const rowASet = new Set('qwertyuiop');
const rowBSet = new Set('asdfghjkl');
const rowCSet = new Set('zxcvbnm');
let result = [];
for(const word of words){
const wordSet = new Set(word.toLowerCase());
let inOneRowSet = false;
//與三個row做差集, 只要其中一個row差集為空集合, 就表示該word屬於該row
if(Array.from(wordSet.difference(rowASet)).length === 0 ||
Array.from(wordSet.difference(rowBSet)).length === 0 ||
Array.from(wordSet.difference(rowCSet)).length === 0)
inOneRowSet = true;
if(inOneRowSet) result.push(word);
}
return result;
};
```
## 初見
- 對words的每個字串的每個字元跑迴圈, 都在同一行就滿足題意
- leetcode submit runtime 13%, memory 88%
```javascript=
var findWords = function(words) {
const rows = ['qwertyuiop','asdfghjkl','zxcvbnm'];
let result = [];
for(let word of words){
const lowerCaseWord = word.toLowerCase();
//判斷word內每個字元是否在同一行
let preRowIndex = -1;
let withSameRowIndex = true;
outLoop:
for(const char of lowerCaseWord){
for(const rowIndex in rows){
if(rows[rowIndex].indexOf(char)>-1){
if(preRowIndex!=-1 && rowIndex!=preRowIndex){
withSameRowIndex = false;
break outLoop;
}
else preRowIndex = rowIndex;
}
}
}
if(withSameRowIndex) result.push(word);
}
return result;
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/keyboard-row/discuss/97913/Easy-Understand-Solution)
###### tags: `leetcode`, `leetcode-easy`, `set`, `array`, `applaction`