LeetCode算法《程序员面试金典(第6版)》 刷题记录(持续更新)

题目1.实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:
输入: s = “leetcode”
输出: false
示例 2:
输入: s = “abc”
输出: true
限制:
0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。

题解

java代码

class Solution {
    public boolean isUnique(String astr) {
        char[] arr = astr.toCharArray();
        int flag = 0;
        for(int i = 0 ; i < arr.length ; i++){
            int index = arr[i] - 'a';
            int x = 1 << index;
            if((flag&x) != 0){
                return false;
            }else {
                flag = flag|x;
            }
        }
        return true;
    }
}

Go代码

func isUnique(astr string) bool {
    arr := []byte(astr)
    flag := 0
    for _, ch := range arr {
        num := int8(ch) - int8('a')
        x := 1 << num
        if (x & flag) == 0 {
            flag = x|flag
        }else {
            return false
        }
    }
    return true
}

题目2.给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例 1:
输入: s1 = “abc”, s2 = “bca”
输出: true
示例 2:
输入: s1 = “abc”, s2 = “bad”
输出: false
说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100

题解

java代码

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if(s1 == null || s2 == null || s1.length() != s2.length()){
            return false;
        }
        char[] arr = s1.toCharArray();
        for(int i = 0 ; i < arr.length ; i++){
            int idx = s2.indexOf(arr[i]);
            if(idx != -1){
                s2 = s2.replaceFirst(String.valueOf(arr[i]), "");
            }else {
                return false;
            }
        }
        return true;
    }
}

Go代码

func CheckPermutation(s1 string, s2 string) bool {
    if len(s1) != len(s2) {
        return false
    }
    arr := []byte(s1)
    for _, ch := range arr{
        if strings.Contains(s2, string(ch)) {
            s2 = strings.Replace(s2, string(ch), "", 1)
        }else {
            return false;
        }
    }
    return true;
}

题目3.回文排列

给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。

回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。

回文串不一定是字典当中的单词。
示例1
输入:“tactcoa”
输出:true(排列有"tacocat"、“atcocta”,等等)

题解

java代码

class Solution {
    public boolean canPermutePalindrome(String s) {
        char[] arr = s.toCharArray();
        int[] dic = new int[128];
        for(int i=0 ; i<arr.length ; i++){
            dic[arr[i]]++;
        }
        int odd = 0;
        for(int i=0 ; i<dic.length ; i++){
            if(dic[i]%2 == 1){
                odd++;
            }
            if(odd > 1){
                return false;
            }
        }
        return true;
    }
}

Go代码(待补充)



题目4.一次编辑

字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例1
输入:
first = “pale”
second = “ple”
输出: True
示例2
输入:
first = “pales”
second = “pal”
输出: False
题解
java代码

class Solution {
    public boolean oneEditAway(String first, String second) {
        if(first == null || second == null) {
            return false;
        }
        int lenDiff = first.length() - second.length();
        int count = 0;
        if(lenDiff <= 1 && lenDiff >= -1) {
            for(int i = 0, j = 0 ; i <first.length() && j<second.length() ; i++, j++) {
                if(first.charAt(i) != second.charAt(j)){
                    if(lenDiff == 1){
                        j--;
                    }else if(lenDiff == -1) {
                        i--;
                    }
                    count++;
                }
            }
        }else {
            return false;
        }
        return count <= 1;
    }
}

Go代码(待补充)



题目5.字符串压缩

字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

示例1
输入:“aabcccccaaa”
输出:“a2b1c5a3”
示例2
输入:“abbccd”
输出:“abbccd”
解释:“abbccd"压缩后为"a1b2c2d1”,比原字符串长度更长。
提示
字符串长度在[0, 50000]范围内。
题解
java代码

class Solution {
   public String compressString(String S) {
       if(S == null || S.length() == 0){
           return S;
       }
       char flag = S.charAt(0);
       int count = 0;
       StringBuffer sb = new StringBuffer();
       for(int i = 0 ; i < S.length() ; i++) {
           if(flag == S.charAt(i)){
               count++;
           }else {
               sb.append(flag).append(count);
               flag = S.charAt(i);
               count = 1;
           }
       }
       sb.append(flag).append(count);
       if(S.length() <= sb.length()){
           return S;
       }else {
           return sb.toString();
       }
   }
}

Go代码(待补充)


题目6.旋转矩阵

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。

不占用额外内存空间能否做到?
示例1
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例2
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
题解
java代码

class Solution {
    public void rotate(int[][] matrix) {
        //j -> i
        //len-i -> j
        int temp;
        int next;
        int len = matrix.length;
        for(int i = 0 ; i < len/2 ; i++) {
            for(int j = i ; j < len - i - 1 ; j++ ){
                temp = matrix[i][j];
                for(int t = 0 ; t < 4 ; t++){
                    //进行4次旋转
                    int nexti = j;
                    int nextj = len - i - 1;
                    next = matrix[nexti][nextj];
                    matrix[nexti][nextj] = temp;
                    temp = next;
                    i = nexti;
                    j = nextj;
                }
            }
        }
    }
}

Go代码(待补充)

7.零矩阵

编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例1
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例2
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
题解
java代码

class Solution {
    public void setZeroes(int[][] matrix) {
        boolean[] arr1 = new boolean[matrix.length];
        boolean[] arr2 = new boolean[matrix[0].length];
        for(int i = 0 ; i < matrix.length ; i++) {
            for(int j = 0 ; j < matrix[0].length ; j++) {
                if(matrix[i][j] == 0){
                    arr1[i] = true;
                    arr2[j] = true;
                }
            }
        }
        for(int i = 0 ; i < arr1.length ; i++) {
            for(int j = 0 ; j < arr2.length ; j++) {
                if(arr1[i] || arr2[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

Go代码(待补充)

题目8.回文链表

编写一个函数,检查输入的链表是否是回文的。
示例1
输入: 1->2
输出: false
示例2
输入: 1->2->2->1
输出: true
**进阶:**你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

题解
关键字:快慢指针找链表中点,反转链表
Java代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode rNode;
        if(fast == null){
            //偶数个节点 后半部分直接反转
            rNode = reverse(slow);
        }else {
            //奇数个节点 slow后移一个之后再反转
            rNode = reverse(slow.next);
        }
        ListNode newNode = head;
        while(rNode != null){
            if(rNode.val != newNode.val) {
                return false;
            }
            rNode = rNode.next;
            newNode = newNode.next;
        }
        return true;
    }
    public ListNode reverse(ListNode head) {
        ListNode pre = null;
        while(head != null) {
            ListNode node = head.next;
            head.next = pre;
            pre = head;
            head = node;
        }
        return pre;
    }
}
题04.03.特定深度节点链表

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

示例:

输入:[1,2,3,4,5,null,7,8]

        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]

题解
关键字:使用Queue作为临时存储结构

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode[] listOfDepth(TreeNode tree) {
        if(tree == null) {
            return new ListNode[0];
        }
        List<ListNode> lst = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(tree);
        while(queue.size() > 0) {
            ListNode head = new ListNode(0);
            ListNode temp = head;
            int size = queue.size();
            while(size > 0){
                TreeNode curTreeNode = queue.poll();
                ListNode curListNode = new ListNode(curTreeNode.val);
                temp.next = curListNode;
                temp = curListNode;
                if(curTreeNode.left != null) {
                    queue.offer(curTreeNode.left);
                }
                if(curTreeNode.right != null) {
                    queue.offer(curTreeNode.right);
                }
                size--;
            }
            lst.add(head.next);
        }
        return lst.toArray(new ListNode[lst.size()]);
    }
}
04.04. 检查平衡性

实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。

示例 1:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]

      1
     / \
    2   2
   / \
  3   3
 / \
4   4

返回 false 。
题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        return Math.abs(getHeight(root.left)-getHeight(root.right)) <= 1 
                && isBalanced(root.left) && isBalanced(root.right) ;
    }

    private int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值