carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1002:查找共用字符(find-common-characters) #177

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。  

示例 1:

输入:words = ["bella","label","roller"] 输出:["e","l","l"] 示例 2:

输入:words = ["cool","lock","cook"] 输出:["c","o"]  

提示:

1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] 由小写英文字母组成

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/find-common-characters

carloscn commented 1 year ago

问题分析

我们以26个英文字母为循环,对其进行查找,字母从a - z:

fn is_contain_then_remove(in_str:&mut String, ch: char) -> bool
{
    if in_str.len() < 1 {
        return false;
    }

    let mut i:usize = 0;
    let in_chars:Vec<char> = in_str.chars().collect();

    for e in &in_chars {
        if *e == ch {
            in_str.remove(i);
            return true;
        }
        i += 1;
    }

    return false;
}

pub fn common_chars(words: Vec<String>) -> Vec<String>
{
    if words.len() < 1 {
        return vec![];
    }

    let mut ret_vec:Vec<String> = vec![];
    let mut word_dup:Vec<String> = words.clone();
    let mut char_push:bool = false;
    let mut count:usize = 0;
    let mut e:u8 = 'a' as u8;

    while e <= 'z' as u8 {
        for str in &mut word_dup {
            if !str.is_empty() {
                if is_contain_then_remove(str, e as char) == true {
                    count += 1;
                }
            }
            if count == words.len() {
                char_push = true;
            }
        }
        count = 0;

        if true == char_push {
            ret_vec.push((e as char).to_string());
            e = e - (1 as u8);
        }
        char_push = false;
        e += 1;
    }

    return ret_vec;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/552228 https://github.com/carloscn/structstudy/commit/83d20f181afed1bb45eb536ffc26f67880acefc4