题解 | #机器人的运动范围#
字典树的实现
http://www.nowcoder.com/practice/a55a584bc0ca4a83a272680174be113b
思想很简单,但是超过时间了
import java.util.*;
public class Solution {
/**
*
* @param operators string字符串二维数组 the ops
* @return string字符串一维数组
*/
//operators[0][0] - 1,operators[0][1] - qwer
//StringBuilder lastStr = new StringBuilder();
ArrayList<String> lastStr = new ArrayList<String>();
ArrayList<String> res = new ArrayList<String>();
public String[] trieU (String[][] operators) {
// write code here
int len = operators.length;
for(int i = 0;i<len;i++){
String str = operators[i][0];
switch(str){
case "1":insert(operators[i][1]);
break;
case "2":delete(operators[i][1]);
break;
case "3":search(operators[i][1]);
break;
case "4":prefixNumber(operators[i][1]);
break;
}//System.out.println(lastStr);
}
return res.toArray(new String[]{});
}
//1.增加
public void insert(String word){
lastStr.add(word);
}
//2.删除
public void delete(String word){
lastStr.remove(String.valueOf(word));
}
//3.查询
public boolean search(String word){
if(lastStr.indexOf(word)!=-1){
res.add("YES");
return true;
}
res.add("NO");
return false;
}
//4.出现次数
public int prefixNumber(String pre){
int cnt = 0;
for(int i = 0;i<lastStr.size();i++){
if(lastStr.get(i).length() < pre.length()) continue;
if(lastStr.get(i).substring(0, pre.length()).equals(pre)){
cnt ++;
}
}
res.add(cnt+"");
return cnt;
}
}