1 计数二进制子串
-
题目:给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。
重复出现的子串要计算它们出现的次数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-binary-substrings -
思路:暴力解法的时间复杂度是O(N*N),会超时。
注意到在处理位置i时,可以利用i-1位置的信息,因此可以通过动态规划进行求解。 -
代码
public int countBinarySubstrings(String s) {
if (s == null || s.length() == 0) {
return 0;
}
// dp[i]表示以s[i]结尾的连续01或10串的长度,如果s[i] != s[i - 1],则dp[i]=1;否则,如果s[i - dp[i - 1] - 1]!=s[i],则dp[i]=dp[i-1]+2
int[] dp = new int[s.length()];
dp[0] = 0;
char[] ch = s.toCharArray();
int res = 0;
for (int i = 1; i < ch.length; i++) {
if (ch[i] != ch[i - 1]) {
dp[i] = 2;
res++;
} else {
if (dp[i - 1] == 0) {
dp[i] = 0;
} else {
int preIndex = i - dp[i - 1] - 1;
if (preIndex >= 0 && ch[preIndex] != ch[i]) {
dp[i] = dp[i - 1] + 2;
res++;
} else {
dp[i] = 0;
}
}
}
}
return res;
}
2 被围绕的区域
-
题目:给定一个二维的矩阵,包含 ‘X’ 和 ‘O’(字母 O)。
找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。
示例:
X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
解释:
被围绕的区间不会存在于边界上,换句话说,任何边界上的 ‘O’ 都不会被填充为 ‘X’。 任何不在边界上,或不与边界上的 ‘O’ 相连的 ‘O’ 最终都会被填充为 ‘X’。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/surrounded-regions -
思路:
因为矩阵边缘的O会决定矩阵中间的O是否能够变成X,所以从边缘的O开始进行dfs即可。
从边缘的O开始dfs,如果位置i j不可以从O变成X,则在boolean remain[i][j]存储true
对于已经访问过的位置i j,将boolean visited[i][j] 置为true,防止在dfs时的栈溢出 (例如输入的矩阵是char[][] c = new char[][]{{‘O’, ‘O’}, {‘O’, ‘O’}};) -
代码
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
return;
}
int r = board.length;
int c = board[0].length;
boolean[][] remain = new boolean[r][c];
boolean[][] visited = new boolean[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (isInBound(i, j, r, c) && board[i][j] == 'O' && !remain[i][j] && !visited[i][j]) {
dfs(i, j, board, remain, visited);
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (!remain[i][j] && board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
3 克隆图
- 题目。给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。
class Node {
public int val;
public List neighbors;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/clone-graph
-
思路。对原始的图从给定的顶点,使用BFS或DFS对图进行遍历,注意如果顶点已经生成了,需要保存下来,下次直接拿,而不是每次重新生成新的。
-
代码。
public class CloneGraph {
public static void main(String[] args) {
CloneGraph cloneGraph = new CloneGraph();
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
node1.neighbors = Arrays.asList(node2, node4);
node2.neighbors = Arrays.asList(node1, node3);
node3.neighbors = Arrays.asList(node2, node4);
node4.neighbors = Arrays.asList(node1, node3);
Node node = cloneGraph.cloneGraph2(node1);
}
HashMap<Node, Node> visitedMap = new HashMap<>();
public Node cloneGraphDFS(Node node) {
if (node == null) {
return null;
}
if (visitedMap.containsKey(node)) {
return visitedMap.get(node);
}
Node n = new Node(node.val, new ArrayList<>());
for (Node nei : node.neighbors) {
n.neighbors.add(cloneGraphDFS(nei));
}
return n;
}
public Node cloneGraph2(Node node) {
if (node == null) {
return null;
}
Map<Integer, Node> val2NodeMap = new HashMap<>();
Set<Integer> processedSet = new HashSet<>();
Queue<Node> queue = new LinkedList<>();
// 遍历原始的图
queue.offer(node);
Node root = new Node(node.val);
val2NodeMap.put(root.val, root);
while (!queue.isEmpty()) {
Node cur = queue.poll();
if (processedSet.contains(cur.val)) {
continue;
}
processedSet.add(cur.val);
Node curClone = cur.val != node.val ? val2NodeMap.computeIfAbsent(cur.val, k -> new Node(cur.val)) : root;
List<Node> neighbors = cur.neighbors;
List<Node> cloneNeighborList = new ArrayList<>();
if (neighbors != null && neighbors.size() != 0) {
for (Node neighbor : neighbors) {
Node n = val2NodeMap.computeIfAbsent(neighbor.val, k -> new Node(neighbor.val));
cloneNeighborList.add(n);
queue.offer(neighbor);
}
curClone.neighbors = cloneNeighborList;
}
}
return root;
}
}
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
4 字符串相乘
-
题目。给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/multiply-strings -
思路。乘法可以转化成加法,例如"789" * “9"可以转化成9个"789” 相加。
-
代码。
public class StringMultiply {
public static void main(String[] args) {
String s1 = "2";
String s2 = "3";
StringMultiply stringMultiply = new StringMultiply();
String multiply = stringMultiply.multiply(s1, s2);
System.out.println(multiply);
String add = stringMultiply.add("2", "3");
System.out.println(add);
}
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
// s1保存较长的串
String s1 = num1.length() > num2.length() ? num1 : num2;
String s2 = s1.equals(num1) ? num2 : num1;
char[] ch1 = s1.toCharArray();
char[] ch2 = s2.toCharArray();
int j = ch2.length - 1;
String res = "";
int suffixZeroCount = 0;
while (j >= 0) {
String tmp = multiply(s1, ch2[j] - '0', suffixZeroCount);
res = add(res, tmp);
suffixZeroCount++;
j--;
}
return res;
}
private String multiply(String s1, int repeatNumber, int suffixZeroCount) {
if (s1.equals("") || repeatNumber == 0) {
return "0";
}
String res = "0";
for (int i = 0; i < repeatNumber; i++) {
res = add(s1, res);
}
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < suffixZeroCount; i++) {
tmp.append("0");
}
return res + tmp;
}
private String add(String s1, String s2) {
char[] ch1 = s1.toCharArray();
char[] ch2 = s2.toCharArray();
int i = ch1.length - 1;
int j = ch2.length - 1;
int carry = 0;
StringBuilder res = new StringBuilder();
while (i >= 0 || j >= 0 || carry != 0) {
int a = i >= 0 ? ch1[i] - '0' : 0;
int b = j >= 0 ? ch2[j] - '0' : 0;
int tmp = a + b + carry;
res.append(tmp % 10);
carry = tmp / 10;
i--;
j--;
}
return res.reverse().toString();
}
}
5 有效的括号
-
题目。给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses -
思路。使用栈解决即可,需要注意如果处理过程中栈空了但是遍历到了右括号,直接返回false即可。
-
代码。
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
for (char c : ch) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if (c == ']' && top != '[' || c == ')' && top != '(' || c == '}' && top != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
图像渲染
- 题目。有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
示例 1:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flood-fill - 思路。典型的Flood类的题目,可以使用DFS或BFS求解。
- 代码。
class Solution {
int[][] direction = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (image == null || image.length == 0 || image[0] == null || image[0].length == 0) {
return image;
}
int r = image.length;
int c = image[0].length;
boolean[][] visited = new boolean[r][c];
boolean[][] need2Colored = new boolean[r][c];
flood(sr, sc, image, visited, need2Colored);
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (need2Colored[i][j]) {
image[i][j] = newColor;
}
}
}
return image;
}
private void flood(int sr, int sc, int[][] image, boolean[][] visited, boolean[][] need2Colored) {
if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || visited[sr][sc]) {
return;
}
visited[sr][sc] = true;
need2Colored[sr][sc] = true;
for (int i = 0; i < 4; i++) {
int newSr = sr + direction[i][0];
int newSc = sc + direction[i][1];
if (newSr >= 0 && newSr < image.length && newSc >=0 && newSc < image[0].length && image[sr][sc] == image[newSr][newSc]) {
need2Colored[newSr][newSc] = true;
flood(newSr, newSc, image, visited, need2Colored);
}
}
}
}