题目参考:https://mp.weixin.qq.com/s/PBXKKCjD2QfDUV45ESPkPg
Question1:替换句子中,出现在list里面的单词,但 加引号 掠过。
思路
1、处理空格,将 left 滑到 非空格处
2、right 指针滑动,单词的终点可能是 空格、逗号,句号。(引号也作为单词一部分,不切分)
3、处理 [left, right) 之间字符
3.1 如果left 是 ", 那么[left, right) 为 example: "hello" → 直接加入res
3.2 如果不是,是普通单词,map是否有,有替换,没有,直接加入
代码参考:
public String solver(String sentence, List<String> words){
HashMap<String, Integer> idxMap = new HashMap<>();
for (int i = 0; i < words.size(); i++){
idxMap.put(words.get(i).toLowerCase(), i);
}
StringBuilder res = new StringBuilder();
char[] cs = sentence.toCharArray();
int i = 0;
while (i < cs.length){
// 空格全部加上
while (i < cs.length && (cs[i] == ' ')){
res.append(cs[i]);
i++;
}
if (i >= cs.length){
break;
}
int right = i;
StringBuilder temp = new StringBuilder();
while (right < cs.length && (cs[right] != ' ' && cs[right] != ',' && cs[right] != '.')){
temp.append(cs[right]);
right++;
}
if (cs[i] == '"'){
res.append(temp);
}else{
String cur = temp.toString().toLowerCase();
if (idxMap.containsKey(cur)){
res.append(idxMap.get(cur));
}else{
res.append(cur);
}
}
if (right < cs.length){
res.append(cs[right]);
}
i = right + 1;
}
return res.toString();
}
先打框架,再满足题目部分要求,也不知道能否过多少
final static int[] DX = {-1, 1, 0, 0};
final static int[] DY = {0, 0, -1, 1};
boolean[][] visited = new boolean[25][25];
static int res = -1;
boolean isExplode = false;
boolean isTrap = false;
public void dfs(int[][] matrix, int i, int j, int cost){
if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length || matrix[i][j] == 1 || visited[i][j]){
return;
}
visited[i][j] = true;
if (matrix[i][j] == 3){
res = Math.max(res, cost);
return;
}
if (matrix[i][j] == 4){
if (isTrap){
for (int k = 0; k < 4; k++){
int x = i + DX[k];
int y = j + DY[k];
dfs(matrix, x, y, cost + 1);
}
}else{
for (int k = 0; k < 4; k++){
int x = i + DX[k];
int y = j + DY[k];
dfs(matrix, x, y, cost + 3);
}
}
}
if (!isExplode && matrix[i][j] == 6){
for (int k = 0; k < 4; k++){
int x = i + DX[k];
int y = j + DY[k];
if (matrix[x][y] == 1){
matrix[x][y] = 0;
}
dfs(matrix, x, y, cost + 1);
}
isExplode = true;
}
if (matrix[i][j] == 0 || matrix[i][j] == 2){
for (int k = 0; k < 4; k++){
int x = i + DX[k];
int y = j + DY[k];
dfs(matrix, x, y, cost + 1);
}
}
visited[i][j] = false;
}