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("  ");
    }
  • 相关阅读:
    今日总结
    今日总结
    今日总结
    k8s controller
    深入k8s:Informer使用及其源码分析
    理解 K8S 的设计精髓之 List-Watch机制和Informer模块
    Unix domain socket 简介
    Linux网络编程——端口复用(多个套接字绑定同一个端口)
    DPVS Tutorial
    dpvs route RTF_KNI
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3921619.html
Copyright © 2011-2022 走看看