小技巧

1.  统计字符串中只出现一次的字符(默认均为小写)。

#include<iostream>
#include<string>
#include<vector>

#define MAX_LENGTH 26


std::vector<char> onlyOneChar(std::string &s){
    int nums[MAX_LENGTH] = {0};
    std::vector<char> vc;
    for(char c: s) ++nums[c - 'a'];
    for(int i = 0; i < MAX_LENGTH; ++i){
        if(nums[i] == 1){
            vc.push_back(i + 'a');
        }
    }
    return vc;
}


int main(void){
    std::string s = "hello world hello china hello leetcode";
    for(char c: onlyOneChar(s)) std::cout<<c<<" ";
    return 0;
}


输出结果:
E:\coding\Algorithms>review.exe
a i n r t w

 2.判断两个字符串中有没有相同的字符

#include<ctype.h>
#include<string.h>

#define MAX_LEN 26

bool IsHaveSameLetter(const char *c1, const char *c2){
    int c1_count[MAX_LEN] = {0};
    int c2_count[MAX_LEN] = {0};
    for(int i = 0; i < strlen(c1); ++i){
        c1_count[tolower(c1[i]) - 'a'] |= 1;
    }
    for(int i = 0; i < strlen(c2); ++i){
        c2_count[tolower(c2[i]) - 'a'] |= 1;
    }
    for(int i = 0; i < MAX_LEN; ++i){
        c1_count[i] += c2_count[i];
    }
    for(int i = 0; i < MAX_LEN; ++i){
        if(c1_count[i] > 1) return true;
    }
    return false;
}

 

posted @ 2019-03-04 22:55  楓羽  阅读(164)  评论(0编辑  收藏  举报