【Leetcode Summary】6-10题总结

6.ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

solution: 这道题我自己想到了简单的方法,但是逻辑太过绕圈了。

官方解法1: 直接把字母按照其对应的行数存入对应的vector,P存入1 A存入2 Y存入3。。。

然后再把每行的string拼接起来

时间复杂度是O(size+row)
官方解法2:Z字符每次的循环为2*row-2; 那么对字符串进行循环,每次处理一个部分,比如 P-L为一个循环

当非第一行或者最后一行时,每次需要插入两个字母,对应的索引也很容易找到

具体代码如下:

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)return s;
    string str = "";
    int cycleLen = numRows*2-2;
    for(int i=0;i<numRows;i++)
    {
        for(int j=0;j+i<s.size();j+=cycleLen)
        {
            str+=s[j+i];
            if(i!=0&&i!=numRows-1&&j+cycleLen-i<s.size()) str+=s[j+cycleLen-i];
        }
    }
        return str;
        }
};

7. Reverse Integer

Easy

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

把数字翻转,但是要注意corner case 就是翻转时候数字溢出的情况,而且要尽量把代码写的简洁:

把数字逆序提取出来通过:

i=x%10;x/=10;

把反转的每一个数字变成原来的数字:

res*=10;

res=res+i;

注意:

解答代码如下:

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

8. String to Integer (atoi)

Medium

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

 

solution:首先是把字符串前面的空格删去,然后判断正负号,接着判断每个字符是否是数字,如果是,就计入结果,否则退出,

还要注意溢出的情况,用Long来存储中间结果,具体看下面代码注释

class Solution {
public:
    int myAtoi(string str) {
        long res = 0;
        int neg=0;
        int index = str.find_first_not_of(' ');
        string s;
        if(index!=string::npos) 
        str= str.substr(index);
        if(str[0]=='-') neg=1;
        if(str[0]=='-'||str[0]=='+') str.erase(str.begin());
         if(str[0]<'0'||str[0]>'9') return 0;
        for(int i = 0;i<str.size();i++)
        {
            if(str[i]<'0'||str[i]>'9') break;
            if(str[i]=='.') break;
              if ((res*10 + str[i]-'0')> INT_MAX) return neg?INT_MIN:INT_MAX;
                //如果这里res 为int类型,则if判断永远为false 因为int类型不可能加出比int_max大
            //的数字,个人理解,欢迎纠正
            
            res=res*10 + str[i]-'0';
        }
        return neg?res*(-1):res;
    }
};

Note:学习到了string的一些成员函数,以及判断整形越界需要用long来存储

9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

solution:不用string 把数字反转判断是否是回文,非常简单,就是把数字经过%10,/10的处理,把结果经过*10,+res的处理

res即为翻转后的数字

代码实现如下:

class Solution {
public:
    bool isPalindrome(int x) {
       if(x<0) return false;
        if(x<10) return true;
        long res = 0;
        int cx = x;
        while(x!=0)
        {
            int tmp = x%10;
            x/=10;
            res*=10;
            res+=tmp;
        }
        if(res==cx)
            return true;
        return false;
    }
};

Note:数字不通过string翻转,可以用%10,/10,*10,+result来实现

10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

solution:关于正则表达式的匹配,这道题还是相当考逻辑的,把我都绕晕了。。。

思路参考这位大佬的博客:

https://www.cnblogs.com/grandyang/p/4461713.html

我自己画了张图帮助理解

Note:遇到这种比较复杂的情况,还是要从最基本的情况考虑,然后再考虑复杂的情况,然后迭代调用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值