0
点赞
收藏
分享

微信扫一扫

【五月集训5.2】—字符串

ixiaoyang8 2022-05-02 阅读 68

请添加图片描述

☘前言☘

开更五月集训专题,由浅入深,深入浅出,飞向大厂!


全文目录


500. 键盘行

500. 键盘行

解题思路

代码

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<string> ans;
        char hash[] = {2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3};
        int n = words.size();
        for(int i = 0;i < n;++i){
            int size = words[i].size(),tmp = hash[words[i][0] - 'a' >= 0 ? words[i][0] - 'a' : words[i][0] - 'a' + ' '], j;
            for(j = 1;j < size;++j)
                if(hash[words[i][j] -'a' >= 0 ? words[i][j] -'a'  : words[i][j] -'a'  + ' '] != tmp)   break;
            if(j == size)   ans.push_back(words[i]);
        }
        return ans;
    }
};

注意的点

  1. 大小写只差一个 一定要记住,看不见的是空格0.0
  2. 可以不用增加变量,用变量j判断是否是中途跳出。

1160. 拼写单词

1160. 拼写单词

解题思路

代码

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int ans = 0;
        int hash[26] = {0};
        int size = chars.size();
        for(auto chari : chars) ++hash[chari - 'a'];

        for(auto wordi : words){
            int j, sizetmp = wordi.size(),tmphash[26] = {0};
            for(j = 0;j < sizetmp;++j)
                if(++tmphash[wordi[j] - 'a'] > hash[wordi[j] - 'a'])    break;

            if(j == sizetmp)   ans += sizetmp;
        }
        return ans;
    }
};

注意的点

  1. 因为每次遍历都要一个临时hash,不如直接建立一个临时hash表

1047. 删除字符串中的所有相邻重复项

1047. 删除字符串中的所有相邻重复项

解题思路

代码

class Solution {
public:
    string removeDuplicates(string s) {
        string ans;
        for(auto ch : s)
            if(!ans.empty() && ans.back() == ch)
                ans.pop_back();
            else
                ans.push_back(ch);
        return ans;
    }
};

注意的点

  1. C++的string提供了类似栈的操作方式,所以直接进行相应的操作就行。

1935. 可以输入的最大单词数

1935. 可以输入的最大单词数

解题思路

代码

class Solution {
public:
    int canBeTypedWords(string text, string brokenLetters) {
        bool hash[26] = {0};
        for(auto brokenLetter : brokenLetters)  hash[brokenLetter - 'a'] = true;
        
        int ans = 0, flag = true;
        for(auto ch : text){
            if(ch == ' '){
                if(flag)    ++ans;
                flag = true;
            }
            else if(hash[ch - 'a']) flag = false;
        }
        if(flag)    ++ans;
        return ans;
    }
};

注意的点

  1. C++的挺好的点就是懒得写类型就auto。。。
  2. 最后一个结束符其实直接到末尾了,所以需要判断再加1

写在最后

今天成功练习了string,学习进度+++++++++++++++++

举报

相关推荐

0 条评论