zoukankan      html  css  js  c++  java
  • Cracking-- 1.1 判断字符串中是否有重复字符

    第三种方法为位运算的方法。

    位运算符: << 左移  & 与 | 或

    #include <iostream>
    #include <string>
    #include <unordered_set>
    #include <vector>
    #include <unordered_map>
    using namespace std;
    
    //时间 O(n) 空间 O(1)
    bool hasSame(string str)
    {
        if(str.size() == 0 )
            return false;
        bool ans = false;
        vector<bool> flag(300,false);
        for(int i = 0; i < str.size(); i++)
        {
            if(flag[str[i]] == true)
                return true;
            flag[str[i]] = true;
        }
        return false;
    }
    //时间 O(n*n) 空间 O(1)
    bool hasSame2(string str)
    {
        if(str.size() == 0)
            return false;
        for(int i = 0; i < str.size(); i++)
            for(int j = i+1; j < str.size(); j++)
            {
                if(str[i] == str[j])
                    return true;
            }
        return false;
    }
    //时间 O(n) 空间 O(1)
    bool hasSame3(string str)
    {
        if(str.size() == 0 )
            return false;
        if(str.size() > 26)
            return true;
    
        int flag = 0;
        for(int i = 0; i < str.size(); i++)
        {
            int num = 1 <<(str[i] - 'a');
             if(flag & num)
                return true;
            flag = flag | num;
        }
        return false;
    }
    int main()
    {
        cout<< hasSame3("abc");
        cout<< hasSame3("aa");
        cout<< hasSame3("abac");
        cout<< hasSame3("bcb");
        cout<< hasSame3("");
        cout<< hasSame3(" ");
        cout<< hasSame3("  ");
    }
  • 相关阅读:
    软件工程个人作业02
    第三周学习进度条
    《构建之法》阅读笔记01
    第二周学习进度条
    软件工程个人作业01
    大道至简第三章读后感
    动手动脑课后实践
    JAVA数字想加并输出
    大道至简第二章读后感
    大道至简读后感
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3921619.html
Copyright © 2011-2022 走看看