leetcode 题解代码整理 6-10题

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 text, int nRows);

convert("PAYPALISHIRING", 3) should
return "PAHNAPLSIIGYIR".

题意:按之字形给如图的字符串,和行数N,求横向输出每排字符串的结果

思路:对于每个位置的字符可用公式求出在原字符串中的位置,逐位输出即可,注意(“A”,2)这种数据和空串

class Solution
{
public:
    string convert(string s, int numRows)
    {
        int len=s.length();
        string ans;

        if (numRows>len) numRows=len;
        if (numRows<=1 )
            return s;

        ans="";

        int k=0;
        int key=2*(numRows-1);
        for (int i=0;i<len;i+=key)
            ans+=s[i];

        int temp=key;
        for (int j=1;j<numRows-1;j++)
        {
            temp-=2;
            for (int i=j;i<len;i+=key)
            {
                ans+=s[i];
                if (i+temp<len)
                    ans+=s[i+temp];
            }
        }

        for (int i=numRows-1;i<len;i+=key)
            ans+=s[i];

        return ans;

    }
};

Reverse
Integer

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

int型数字反转输出,注意处理翻转后越界的情况

class Solution
{
public:
    int reverse(int x)
    {
        if (overflow(x)==true)
            return 0;
        int ret=0;
        while (x!=0)
        {
            ret=ret*10+x%10;
            x/=10;
        }
        return ret;
    }

private:
    bool overflow(int x)
    {
        if (x/1000000000==0)
            return false;
        else
        if (x == INT_MIN)
            return true;

        x=abs(x);
        for (int cmp=463847412;cmp!=0;cmp/=10,x/=10)
            if (x%10>cmp%10)
                return true;
            else
            if (x%10<cmp%10)
                return false;
        return false;
    }
};

String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

模拟atoi函数,注意读入前导空串和非法字符以及超界情况

class Solution
{
public:
    int myAtoi(string str)
    {
        int len,i,flag,j;
        long long temp;
        len=str.length();
        if (len==0)
            return 0;

        i=0;
        while (str[i]==' ' )
            i++;

        flag=1;
        if (str[i]=='+')
            i++;
        else
        if (str[i]=='-')
        {
            i++;
            flag=-1;
        }

        temp=0;
        for (j=i;j<len;j++)
        {
            if (str[j]<'0' || str[j]>'9') break;
            temp=temp*10+str[j]-'0';

            if (temp>INT_MAX)
            {
                if (flag==1) return INT_MAX;
                else return INT_MIN;
            }
        }
        temp*=flag;
        return (int)temp;

    }
};

Palindrome Number

Determine
whether an integer is a palindrome. Do this without extra space.

判断数字是否为回文串

class Solution {
public:
    bool isPalindrome(int x)
    {
        int n=0;
        int num[20];
        if (x<0) return false;
        while (x!=0)
        {
            num[n++]=x%10;
            x/=10;
        }
        n--;
        int i=0;
        while (i<n)
            if (num[i++]!=num[n--]) return false;
        return true;
    }
};

Regular Expression Matching

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).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
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

正则表达式的匹配,只需要考虑“.‘和”*“即可

递归求解

class Solution
{
public:
    bool isMatch(string s, string p)
    {
        if (p.size()==0)
        {
            if (s.size()==0) return true;
            else return false;
        }

        if (p[1]!='*')
        {
            if (p[0]==s[0] || (p[0]=='.' && s.size()!=0))
                return isMatch(s.substr(1),p.substr(1));
            else
                return false;
        }
        else
        {
            int a=0;
            while (p[0]==s[a] || (p[0]=='.' && s.size()!=0))
            {
                if (isMatch(s.substr(a),p.substr(2)))
                    return true;
                a++;
             //   if (a==s.size()) break;
            }

            return false;
        }

    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-07-29 19:21:09

leetcode 题解代码整理 6-10题的相关文章

leetcode 题解代码整理 36-40题

Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. 判断数独当前状态是否合法 class Solut

leetcode 题解代码整理 1-5题

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please no

leetcode 题解代码整理 31-35题

Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending orde

leetcode 题解代码整理 21-25题

Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 合并两个有序链表 /** * Definition for singly-linked list. * struct ListNode { * int val; * Li

【OCP|052】OCP题库更新,052最新考题及答案整理-第10题

10.Which two are true about consistent database backups? A) They can only be taken when a RECOVERY CATALOG is used. B) They can only be taken if the database Is in ARCHIVELOG mode. C) They can only be taken If shutdown NORMAL, TRANSACTIONAL, or IMMED

Leetcode第1题至第10题 思路分析及C++实现

笔者按照目录刷题,对于每一道题,力争使用效率最高(时间复杂度最低)的算法,并全部通过C++代码实现AC.(文中计算的复杂度都是最坏情况复杂度) 因为考虑到大部分读者已经在Leetcode浏览过题目了,所以每道题都按照 解题思路 -> 实现代码 -> 问题描述 的顺序进行讲解. (笔者目前已刷 40 题,已更新解法 10 题,最近一段时间会频繁更新)可以点击下方链接,直达gitbook: https://codernie.gitbooks.io/leetcode-solutions/conten

【题解整理】二分题

[题解整理]二分题 题目类型: 二分查找: 二分答案. 大致解题思路: 查找注意有序和返回值: 浮点数注意精度: 整数注意返回值,建议另外维护一个变量,用于储存可行解. 题目 分类 传送门 WA点 poj 2785 二分查找 题解 lightoj 1088 二分查找 题解 lightoj 1307 二分查找 题解 longlong poj 2456 整数二分答案 题解 poj 3104 整数二分答案 题解 poj 3258 整数二分答案 题解 poj 3273 整数二分答案 题解 lightoj

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible