c++刷题(24/100)正则匹配与位运算

题目1:正则表达式匹配

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

思路:这道题很快就能想到递归,但是由于*的存在使得判别比较多,所以也感觉比较难,网上查了答案,这个答案的精髓在于超出索引的部分返回0来表示,这样就少写了很多数组越界的判断。

class Solution {
public:
    bool isMatch(char a,char b){
        if(a==b||b=='.'){
            if(a!=0)return true ;
        }
        return false ;
    }
    char getChar(string s,int idx){
        if(s.length()>idx) {
            return s[idx] ;
        }
        return 0 ;
    }
    bool match(string str, string pattern)
    {
        int slen = str.length() ;
        int plen = pattern.length() ;
        if(slen==0&&plen==0) return true ;
        char s0 = getChar(str,0) ;
        char p0 = getChar(pattern,0) ;
        char p1 = getChar(pattern,1) ;
        if(isMatch(s0,p0)||p1=='*'){
            if(p1=='*'){
                bool isZeroFit =  match(str.substr(0),pattern.substr(2)) ;//0的情况
                if(isZeroFit) return true ;
                int i = 0 ;
                while(i<slen&&isMatch(getChar(str,i),p0)){
                    bool res = match(str.substr(i+1),pattern.substr(2)) ;
                    if(res) return true ;
                    i++ ;
                }
                return false ;
            }else{
                if(slen==0) return false ;
                return match(str.substr(1),pattern.substr(1)) ;
            }
        }
        return false ;
    }
};

 题目二:只出现一次的数字 III

给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

示例 :

输入: [1,2,1,3,2,5]
输出: [3,5]
思路:要用异或的方法,两个相同的数异或是0,所以当只有一个数不同时,一直异或就能找到那个数,两个数的情况要找到这两个数异或结果后不同的那一位,然后将数组分组,按组异或找出这两个数
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        if (nums.size() < 2)return vector<int>();
        else if (nums.size() == 2)return nums;
        int all = 0;
        for (auto num:nums)
            all ^= num;
        int k = 0;
        while (true) {
            if (1 & all>>k)break;
            k++ ;
        }
        int res1 = 0, res2 = 0;
        for (auto num : nums) {
            if (num>>k & 1)
                res1 ^= num;
            else res2 ^= num;
        }
        vector<int> result;
        result.push_back(res1);
        result.push_back(res2);
        return result;
    }
};

 题目三:二进制中1的个数

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

思路:最简单的想法是将给的数不断右移,每次右移之后如果结果&1为1,那么证明那一位有1,计数的变量就加一,然而这么做会时间超出,正确的解法是再做一个小判断,判断n&=n-1 是否为0,因为n&=n-1这种判别方法可以忽略掉bit位上0 的部分

class Solution {
public:
     int  NumberOf1(int n) {
         int ans = 0;
         while(n!=0){
             n&=n-1 ;
             ans++ ;
         }
         return ans ;
     }
};

 

posted @ 2018-07-25 14:24  mask_天俊  阅读(233)  评论(0编辑  收藏  举报