874.模拟行走机器人
代码逻辑:
使用哈希setp存储障碍物
变量:结果 --- > 过程中最大的欧式和,进行不断地迭代
方向
坐标值 x,y 方向值 direction
指令的遍历:三种情况:
方向的负数 -1 -2
方向值的一个变化
正数:在某个方向的前进多少位
没有遇到障碍物,一直往前走 com 个单位长度
没有遇到障碍物:三个条件
指令-- 为正数 --- while循环
障碍物的key不存在当前值
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int result = 0;
int x = 0, y = 0;
int direction = 0;
int[][] direxy = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
HashSet<String> obstaclesSet = new HashSet<>();
for (int[] obs : obstacles) {
// 以坐标的形式存储
obstaclesSet.add(obs[0] + "," + obs[1]);
}
for(int com : commands){
if(com == -1){
direction = (direction == 3) ? 0 : direction + 1;
} else if(com == -2){
direction = (direction == 0) ? 3 : direction - 1;
} else {
while(com-- > 0 && !obstaclesSet.contains((x + direxy[direction][0]) + "," + (y + direxy[direction][1]))){
x += direxy[direction][0];
y += direxy[direction][1];
}
result = Math.max(result,x * x + y * y);
}
}
return result;
}
}
49.字母异位词分组
代码逻辑:
变量:哈希map --- key为字母和其个数,value是他们的同位词的列表 --- 最后 map.values()
就可以获取输出
过程: 遍历所有的字符串数组 ---- 将其变为key
将其变为key : 统计字母的个数 使用StringBuffer
将其存进map
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for(String str : strs){
int[] counts = new int[26];
for(char c : str.toCharArray()){
counts[c - 'a']++;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 26; i++) {
if(counts[i] != 0){
sb.append((char) ('a' + i));
sb.append(counts[i]);
}
}
String key = sb.toString();
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key,list);
}
return new ArrayList<List<String>>(map.values());
}
}
242.(举一反三)有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length() ) return false;
String key1 = getKey(s);
String key2 = getKey(t);
if(!key1.equals(key2)) return false;
return true;
}
String getKey(String str){
int[] counts = new int[26];
for(char c : str.toCharArray()){
counts[c - 'a']++;
}
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < 26 ; i++){
if (counts[i] != 0){
sb.append((char) ('a' + i));
sb.append(counts[i]);
}
}
return sb.toString();
}
}