Skip to content

add 0500 and 0501 java version #255

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions solution/0500-0599/0500.Keyboard Row/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {

public String[] findWords(String[] words) {
if (words == null) {
return null;
}
ArrayList<String> list = new ArrayList<>();
String[] keyboards = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
for (int i = 0; i < words.length; i++) {
String word = words[i].toLowerCase();
for (int j = 0; j < keyboards.length; j++) {
// 先用word首字符确定属于哪一行
if (keyboards[j].indexOf(word.charAt(0)) > -1) {
// 判断word字符串所有字符是否都属于同一行
boolean match = match(keyboards[j], word, list);
if (match) {
list.add(words[i]);
}
break;
}
}
}
return list.toArray(new String[list.size()]);
}

private boolean match(String keyboard, String word, ArrayList<String> list) {
for (int i = 1; i < word.length(); i++) {
if (keyboard.indexOf(word.charAt(i)) < 0) {
return false;
}
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
int cur = 0;
TreeNode preNode = null;

public int[] findMode(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
findMode(root, list);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}

private void findMode(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
findMode(root.left, list);
if (preNode != null && root.val == preNode.val) {
cur++;
} else {
cur = 1;
}
if (max < cur) {
max = cur;
list.clear();
list.add(root.val);
} else if (max == cur) {
list.add(root.val);
}
preNode = root;
findMode(root.right, list);
}
}