Leetcode

持续更新中。。。。。。。。。。。。。。

day 20230815

833. 字符串中的查找与替换

class Solution {
     public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        if (s== null || s.isEmpty()) {
            return s;
        }
        // sort
        List<Node> list = new ArrayList<>();
        for (int i = 0; i < indices.length; i++ ) {
            list.add(new Node(indices[i], sources[i], targets[i]));
        }
        list.sort(new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return Integer.compare(o1.index, o2.index);
            }
        });
       for (int i = 0; i < list.size(); i++ ) {
           indices[i] = list.get(i).index;
           sources[i] = list.get(i).source;
           targets[i] = list.get(i).target;
       }
        // sort index.
        int len = indices.length;
        // from end to start.
        for (int i = len -1; i >=0; i--) {
            int index = indices[i];
            String source = sources[i];
            String target = targets[i];
            int iIndex = s.indexOf(source, index);
            if (iIndex == index) {
                StringBuilder sb = new StringBuilder(s);
                sb.replace(index, index + source.length(), target);
                s = sb.toString();
            }
        }
        return s;
    }
    
    class Node {
        public int index;
        public String source, target;
        Node(int index, String source, String targert) {
            this.index = index;
            this.source = source;
            this.target = targert;
        }
    }
}

day 20230814

617. 合并二叉树


// merge right Tree to left
public class num617 {

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        // merge left
        if (root1.left == null) {
            root1.left = root2.left;
        } else {
            mergeTrees(root1.left, root2.left);
        }
        // merge right
        if (root1.right == null) {
            root1.right = root2.right;
        } else {
            mergeTrees(root1.right, root2.right);
        }
        // merge root
        root1.val = root1.val + root2.val;
        return root1;
    }
}

day 20230811



/**
 * 给你一个正方形矩阵 mat,请你返回矩阵对角线元素的和。
 * 

* 请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和 *

* 不包括 相交的元素只计算一次 *

* 输入:mat = [[1,2,3], * [4,5,6], * [7,8,9]] * 输出:25 * 解释:对角线的和为:1 + 5 + 9 + 3 + 7 = 25 * 请注意,元素 mat[1][1] = 5 只会被计算一次。 */ public class num1572 { public int diagonalSum(int[][] mat) { int res = 0; if (mat.length == 0 || mat.length != mat[0].length) return 0; int rows = mat.length; for (int i = 0; i < rows; i++) { res += mat[i][i] + mat[i][rows - 1 - i]; if (i == rows - 1 - i) { res -= mat[i][i]; } } return res; } }

你可能感兴趣的:(Leetcode,leetcode)