字符串题目杂记

前言:
主要是字符串处理的题目,有时候感觉很简单却处理不好-= 这里就作为我的字符串题目笔记吧,主要来自于 leetcode 周赛的第一题 。题目就放英文吧,也锻炼一下英文阅读能力,小陈,加油!
—— 2021.8.8


LeetCode 5838. 检查字符串是否为数组前缀(check-if-string-is-a-prefix-of-array)

Given a string s and an array of strings words, determine whether s is a prefix string(前缀字符串) of words.

A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.

Return true if s is a prefix string of words, or false otherwise.

Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating “i”, “love”, and “leetcode” together.

Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • 1 <= s.length <= 1000

words[i] and s consist of only lowercase English letters.

思路:
判断s是否是前缀数组,就要求s是 完全 由字符串数组中的元素 按顺序 组成。那么每次取出一个元素拼接组成str,并进行判断。s等于str就返回true,循环结束返回false

c++代码:

class Solution {
public:
    bool isPrefixString(string s, vector<string>& words) {
        string str;
        for(int i = 0; i < words.size(); i ++ ){
            str += words[i];
            if(str == s) return true;
        }
        return false;
    }
};

python3代码:

class Solution:
    def isPrefixString(self, s: str, words: List[str]) -> bool:
        text = ''
        for w in words:
            text = text + w
            if s == text: return True
        return False

LeetCode 1957. 删除字符使字符串变好(delete-characters-to-make-fancy-string)

A fancy string is a string where no three consecutive characters are equal.

Given a string s, delete the minimum possible number of characters from s to make it fancy.

Return the final string after the deletion. It can be shown that the answer will always be unique.

Example 1:

Input: s = “leeetcode
Output:leetcode
Explanation:
Remove an ‘e’ from the first group of 'e’s to create “leetcode”.
No three consecutive characters are equal, so return “leetcode”.

Example 2:

Input: s = “aaabaaaa
Output:aabaa
Explanation:
Remove an ‘a’ from the first group of 'a’s to create “aabaaaa”.
Remove two 'a’s from the second group of 'a’s to create “aabaa”.
No three consecutive characters are equal, so return “aabaa”.

Example 3:

Input: s = “aab
Output: “aab”
Explanation: No three consecutive characters are equal, so return “aab”.

Constraints:

  1. 1 <= s.length <= 105
  2. s consists only of lowercase English letters.

思路:
如果s的长度小于3,说明不可能有连续的3个相同字母,直接返回即可;
否则从第三位开始循环判断,如果某一位和前两位都不相同,就加入结果数组中

c++代码:

class Solution {
public:
    string makeFancyString(string s) {
        string ans;
        if(s.size() < 3)
            return s;
        
        ans += s[0];
        ans += s[1];
        for(int i = 2; i < s.size(); i ++){
            char c1 = s[i - 1];
            char c2 = s[i - 2];
            if(!(s[i] == c1 && s[i] == c2))
                ans += s[i];
        }
        return ans;
    }
};

python3代码:

class Solution:
    def makeFancyString(self, s: str) -> str:
        ans = ''
        if len(s) < 3:
            ans = s
        else:
            ans = ans + s[:2]
            for i in range(2, len(s)):
                if s[i-1] != s[i-2] or s[i] != s[i-1]:
                    ans = ans + s[i]
        return ans 

LeetCode 1945. 字符串转化后的各位数字之和(sum-of-digits-of-string-after-convert)

You are given a string s consisting of lowercase English letters, and an integer k.

First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace ‘a’ with 1, ‘b’ with 2, …, ‘z’ with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.

For example, if s = “zbax” and k = 2, then the resulting integer would be 8 by the following operations:

Convert: “zbax” ➝ “(26)(2)(1)(24)” ➝ “262124” ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8
Return the resulting integer after performing the operations described above.

Example 1:

Input: s = “iiii”, k = 1
Output: 36
Explanation: The operations are as follows:

  • Convert: “iiii” ➝ “(9)(9)(9)(9)” ➝ “9999” ➝ 9999
  • Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
    Thus the resulting integer is 36.
    Example 2:

Input: s = “leetcode”, k = 2
Output: 6
Explanation: The operations are as follows:

  • Convert: “leetcode” ➝ “(12)(5)(5)(20)(3)(15)(4)(5)” ➝ “12552031545” ➝ 12552031545
  • Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
  • Transform #2: 33 ➝ 3 + 3 ➝ 6
    Thus the resulting integer is 6.
    Example 3:

Input: s = “zbax”, k = 2
Output: 8

Constraints:

  • 1 <= s.length <= 100
  • 1 <= k <= 10
  • s consists of lowercase English letters.

思路:
每次读取一位字符,然后转化为对应的数字,累加就能得到操作一次的结果,然后再执行k-1次即可。
有些字母对应的数字,是两位数(例如z就是26),求和的时候要分别把十位和个位加上

c++代码:

class Solution {
public:
    int getLucky(string s, int k) {
        int ans = 0;
        for(int i = 0; i < s.size(); i ++ ){
            int tmp;
            // tmp 表示一位字母转化成的数字,该数字可能大于10
            tmp = s[i] - 'a' + 1;
            ans += tmp / 10;    // 加上个位数字
            ans += tmp % 10;    // 加上十位数字
        }
        // 已经执行了一遍 还需要执行k-1趟
        for(int i = 0; i < k - 1; i ++ ){
            int tmp = ans;
            ans = 0;
            while(tmp){
                ans += tmp % 10;
                tmp /= 10;
            }
        }
        return ans;
    }
};

LeetCode 1941. 检查是否所有字符出现次数相同( Check if All Characters Have Equal Number of Occurrences)

Given a string s, return true if s is a good string, or false otherwise.

A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).

Example 1:

Input: s = “abacbc”
Output: true
Explanation: The characters that appear in s are ‘a’, ‘b’, and ‘c’. All characters occur 2 times in s.
Example 2:

Input: s = “aaabb”
Output: false
Explanation: The characters that appear in s are ‘a’ and ‘b’.
‘a’ occurs 3 times while ‘b’ occurs 2 times, which is not the same number of times.

Constraints:

1 <= s.length <= 1000
s consists of lowercase English letters.

c++实现:

class Solution {
public:
    bool areOccurrencesEqual(string s) {
        map<char, int> mp;
        set<int> se;
        bool flag = true;

        for(auto ch : s)
            mp[ch]++;
        
        for(auto [k, v] : mp)
            se.insert(v);

        return se.size() == 1;
    }
};

LeetCode 5843. 作为子字符串出现在单词中的字符串数目

number-of-strings-that-appear-as-substrings-in-word

Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: patterns = [“a”,“abc”,“bc”,“d”], word = “abc”
Output: 3
Explanation:

  • “a” appears as a substring in “abc”.
  • “abc” appears as a substring in “abc”.
  • “bc” appears as a substring in “abc”.
  • “d” does not appear as a substring in “abc”.
    3 of the strings in patterns appear as a substring in word.
    Example 2:

Input: patterns = [“a”,“b”,“c”], word = “aaaaabbbbb”
Output: 2
Explanation:

  • “a” appears as a substring in “aaaaabbbbb”.
  • “b” appears as a substring in “aaaaabbbbb”.
  • “c” does not appear as a substring in “aaaaabbbbb”.
    2 of the strings in patterns appear as a substring in word.
    Example 3:

Input: patterns = [“a”,“a”,“a”], word = “ab”
Output: 3
Explanation: Each of the patterns appears as a substring in word “ab”.

Constraints:

1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i] and word consist of lowercase English letters.

python3实现:

class Solution:
    def numOfStrings(self, patterns: List[str], word: str) -> int:
        count = 0
        for p in patterns:
            if p in word:
                count = count + 1
        return count

c++实现:

class Solution {
public:
    int numOfStrings(vector<string>& patterns, string word) {
        int res = 0;
        for (auto s: patterns)
            if (word.find(s) != s.npos)
                res ++ ;
        return res;
    }
};

LeetCode 5855. 找出数组中的第 K 大整数

find-the-kth-largest-integer-in-the-array

You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.

Return the string that represents the kth largest integer in nums.

Note: Duplicate numbers should be counted distinctly. For example, if nums is [“1”,“2”,“2”], “2” is the first largest integer, “2” is the second-largest integer, and “1” is the third-largest integer.

Example 1:

Input: nums = [“3”,“6”,“7”,“10”], k = 4
Output: “3”
Explanation:
The numbers in nums sorted in non-decreasing order are [“3”,“6”,“7”,“10”].
The 4th largest integer in nums is “3”.
Example 2:

Input: nums = [“2”,“21”,“12”,“1”], k = 3
Output: “2”
Explanation:
The numbers in nums sorted in non-decreasing order are [“1”,“2”,“12”,“21”].
The 3rd largest integer in nums is “2”.
Example 3:

Input: nums = [“0”,“0”], k = 2
Output: “0”
Explanation:
The numbers in nums sorted in non-decreasing order are [“0”,“0”].
The 2nd largest integer in nums is “0”.

Constraints:

  • 1 <= k <= nums.length <= 104
  • 1 <= nums[i].length <= 100
  • nums[i] consists of only digits.
  • nums[i] will not have any leading zeros.

思路:
将数组元素从大到小排序后输出第k大(下标为k-1)的数
string的排序和数字排序不一样,string的排序认为"22"比"111"大,因此需要重写cmp

c++实现:

bool cmp(string &a, string &b){
    return a.size() == b.size() ? a > b : a.size() > b.size();
}

class Solution { 
public:
    string kthLargestNumber(vector<string>& nums, int k) {
        sort(nums.begin(), nums.end(), cmp);
        return nums[k-1];
    }
};

你可能感兴趣的:(算法学习,字符串)