LeetCode之双指针(1)

88.Merge Sorted Array
题目链接:

https://leetcode.com/problems/merge-sorted-array/

题目描述:

给定两个有序数组,将两个数组合并。

题目分析:

因为两个数组大小给定了,可以用尾插法。

代码:
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int iM=m-1,iN=n-1,cur=m+n-1;
        while(iM>=0 && iN>=0){
            nums1[cur--]=nums1[iM]>nums2[iN]? nums1[iM--]:nums2[iN--];
        }
        while(iN>=0){
            nums1[cur--]=nums2[iN--];
        }
    }
};
125. Valid Palindrome
题目链接:

https://leetcode.com/problems/valid-palindrome/

题目描述:

判断字符串是否是回文。

For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.

题目分析:

比较麻烦的是字符串中的非字母和数字的处理。

代码:
class Solution {
public:
    bool isAlphanumeric(char ch){
        if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (ch>='0' && ch<='9')){
            return true;
        }
        return false;
    }
    bool isPalindrome(string s) {
        int high=s.size()-1;
        int low=0;
        bool flag=true;
        while(low<high){
            flag=true;
            if(!isAlphanumeric(s[low])){
                low++;
                flag=false;
            }
            if(!isAlphanumeric(s[high])){
                flag=false;
                high--;
            }
            if(flag){
                s[low]=tolower(s[low]);
                s[high]=tolower(s[high]);
                if(s[low]!=s[high]){
                    return false;
                }
                low++;
                high--;
            }
        }
        return true;
    }
};
28. Implement strStr()
题目链接:

https://leetcode.com/problems/implement-strstr/

题目描述:

找出子串在主串第一次出现的下标索引。

题目分析:

朴素模式匹配算法。

代码:
class Solution {
public:
    int strStr(string haystack, string needle) {
        int lenH=haystack.size();
        int lenN=needle.size();
        int i=0,j=0;
        while(i<lenH &&j<lenN){
            if(haystack[i]==needle[j]){
                i++;
                j++;
            }
            else{
                i=i-j+1;
                j=0;
            }
        }
        if(j>=lenN){
            return i-j;
        }
        else{
            return -1;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值