8月5日趋势科技笔试题-AK代码
## 第一题,文本替换
- 每次取最左端的值进行替换
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param my_template string字符串
* @param keys string字符串一维数组
* @param values string字符串一维数组
* @return string字符串
*/
public String token_replace (String my_template, String[] keys, String[] values) {
// write code here
Map<String, String> map = new HashMap<>();
for(int i = 0; i < keys.length; ++i) map.put(keys[i], values[i]);
StringBuilder ans = new StringBuilder(my_template);
while(true){
int minIndex = my_template.length();
String target = "", source = "";
// 每次取匹配的最左端的值 进行替换
boolean flag = false;;
for(String temp : keys){
String next = "%"+ temp +"%";
int index = ans.indexOf(next);
if(index != -1){
flag = true;
if(index < minIndex){
minIndex = index;
source = next;
target = temp;
}
}
}
if(!flag) break;
ans.replace(minIndex, minIndex + source.length(), map.get(target));
}
return ans.toString();
}
} ## 第二题
- dfs + 记录当前遍历区域的 1 的坐标
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* Return the graph count and max distance of graph edge
* @param graph int整型二维数组
* @return int整型一维数组
*/
int[][] dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
int[][] arr;
boolean[][] visit;
int m, n;
int num = 0, maxDis = 0;
public int[] solve (int[][] graph) {
// write code here
arr = graph;
m = arr.length;
if(m == 0) return new int[2];
n = arr[0].length;
visit = new boolean[m][n];
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(!visit[i][j] && arr[i][j] == 1){
++num;
dfs(i, j, new ArrayList<>());
}
}
}
return new int[]{num, maxDis};
}
void dfs(int x, int y, List<int[]> list){
if(x < 0 || x >= m || y < 0 || y >= n || arr[x][y] == 0 || visit[x][y]) return;
visit[x][y] = true;
// 求该点 与当前区域的距离
for(int[] pre : list){
int cur = Math.abs(pre[0] - x) + Math.abs(pre[1] - y);
maxDis = Math.max(maxDis, cur);
}
list.add(new int[]{x, y});
for(int i = 0; i < dir.length; ++i){
int nx = x + dir[i][0], ny = dir[i][1] + y;
dfs(nx, ny, list);
}
}
}
查看7道真题和解析