美文网首页Leetcode程序员
LeetCode算法代码笔记(6-10)

LeetCode算法代码笔记(6-10)

作者: cpacm | 来源:发表于2017-05-25 14:43 被阅读189次

    给自己的目标:[LeetCode](https://leetcode.com/ "Online Judge Platform") 上每日一题

    在做题的过程中记录下解题的思路或者重要的代码碎片以便后来翻阅。
    项目源码:github上的Leetcode

    6. ZigZag Conversion

    题目:将一行字符串按给出的行数竖向锯齿形排列,再按行输出。

    input:PAYPALISHIRING
    P   A   H   N
    A P L S I I G
    Y   I   R
    ouput:PAHNAPLSIIGYIR
    

    一道找规律的题目
    对于每一层垂直元素的坐标 (i,j)= (j+1 )n +i;对于每两层垂直元素之间的插入元素(斜对角元素),(i,j)= (j+1)n -i

    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1) return s;
            int len = s.length();
            int span = numRows * 2 - 2;
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < numRows; i++) {
                int j = i;
                while (j < len) {
                    sb.append(s.charAt(j));
                    if (j % span == 0 || j % span == (numRows - 1)) {
                        j += span;
                    } else {
                        int k = j + (span - i * 2);
                        if (k < len) {
                            sb.append(s.charAt(k));
                        }
                        j += span;
                    }
                }
            }
            return sb.toString();
        }
    }
    

    7. Reverse Integer

    题目:数字反转,当反转后数字超出32位时,设值为0

    Example1: x = 123, return 321
    Example2: x = -123, return -321 
    

    先将数字转换为字符串,然后利用字符串反转。当反转后数字溢出时,使用try...catch 捕获。

    public class Solution {
        public int reverse(int x) {
            boolean prefix = x < 0;
            int ax = Math.abs(x);
            StringBuffer sb = new StringBuffer();
            sb.append(ax);
            String s = sb.reverse().toString();
            int value = 0;
            try {
                value = Integer.valueOf(s);
            } catch (NumberFormatException e) {
                value = 0;
            }
            if (prefix) {
                return -value;
            }
            return value;
        }
    }
    

    8. String to Integer (atoi)

    题目:字符串转换为数字。需要注意的是允许字符串前面出现的空格和当字符串中出现数字之外的值时要输出前面的数值。数值溢出时取最大或者最小值。

    public class Solution {
        public int myAtoi(String str) {
            int value = 0;
            int prefix = 1;
            boolean isFirst = true;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c == ' ' && isFirst) {
                    continue;
                }
                if (isFirst && (c == '+' || c == '-')) {
                    if (c == '-') {
                        prefix = -1;
                    }
                    isFirst = false;
                    continue;
                }
                if (c >= '0' && c <= '9') {
                    isFirst = false;
                    int newValue = value * 10 + c - '0';
                    if (newValue / 10 != value) {
                        if (prefix < 0) {
                            return Integer.MIN_VALUE;
                        } else {
                            return Integer.MAX_VALUE;
                        }
                    }
                    value = value * 10 + c - '0';
                } else {
                    return value * prefix;
                }
    
            }
            return value * prefix;
        }
    }
    

    9. Palindrome Number

    题目:回文数字

    将数字反转判断是否相等即可

    public class Solution {
        public boolean isPalindrome(int x) {
            if (x < 0) return false;
            if (x == 0) return true;
            long index = 0;
            int s = x;
            while (x > 0) {
                index = index * 10 + x % 10;
                x = x / 10;
            }
    
            return index == s;
        }
    }
    

    10. Regular Expression Matching

    题目:'.' 匹配任一字符,'*'匹配前面数字0或多个字符。输入一行字符串和一行匹配串,判断是否匹配。

    isMatch("aa","a") → false
    isMatch("aa","aa") → true
    isMatch("aaa","aa") → false
    isMatch("aa", "a*") → true
    isMatch("aa", ".*") → true
    isMatch("ab", ".*") → true
    isMatch("aab", "c*a*b") → true
    
    

    递归和动态规划两种解法。自己先使用的递归方法,耗时有点长。

    1, If p.charAt(j) == s.charAt(i) :  dp[i][j] = dp[i-1][j-1];
    2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
    3, If p.charAt(j) == '*': 
       here are two sub conditions:
                   1   if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2]  //in this case, a* only counts as empty
                   2   if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':
                                  dp[i][j] = dp[i-1][j]    //in this case, a* counts as multiple a 
                               or dp[i][j] = dp[i][j-1]   // in this case, a* counts as single a
                               or dp[i][j] = dp[i][j-2]   // in this case, a* counts as empty
    
    public class Solution {
        public boolean isMatch(String s, String p) {
                if (s == null || p == null) {
                    return false;
                }
                int m = s.length();
                int n = p.length();
                boolean[][] dp = new boolean[m + 1][n + 1];
                dp[0][0] = true;
                for (int j = 0; j < n; j++) {
                    if (p.charAt(j) == '*') {
                        dp[0][j + 1] = dp[0][j - 1];
                    }
                }
                for (int i = 0; i < m; i++) {
                    for (int j = 0; j < n; j++) {
                        if (p.charAt(j) == '.') {
                            dp[i + 1][j + 1] = dp[i][j];
                        }
                        if (p.charAt(j) == s.charAt(i)) {
                            dp[i + 1][j + 1] = dp[i][j];
                        }
                        if (p.charAt(j) == '*') {
                            if (p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') {
                                dp[i + 1][j + 1] = dp[i + 1][j - 1];
                            } else {
                                dp[i + 1][j + 1] = dp[i + 1][j - 1] || dp[i + 1][j] || dp[i][j + 1];
                            }
                        }
                    }
                }
                return dp[m][n];
            }
        }
    

    相关文章

      网友评论

        本文标题:LeetCode算法代码笔记(6-10)

        本文链接:https://www.haomeiwen.com/subject/zdczxxtx.html