carloscn / structstudy

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

leetcode2287: Rearrange Characters to Make Target String #375

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.

Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.

Example 1:

Input: s = "ilovecodingonleetcode", target = "code" Output: 2 Explanation: For the first copy of "code", take the letters at indices 4, 5, 6, and 7. For the second copy of "code", take the letters at indices 17, 18, 19, and 20. The strings that are formed are "ecod" and "code" which can both be rearranged into "code". We can make at most two copies of "code", so we return 2.

Example 2:

Input: s = "abcba", target = "abc" Output: 1 Explanation: We can make one copy of "abc" by taking the letters at indices 0, 1, and 2. We can make at most one copy of "abc", so we return 1. Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc".

Example 3:

Input: s = "abbaccaddaeea", target = "aaaaa" Output: 1 Explanation: We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12. We can make at most one copy of "aaaaa", so we return 1.

Constraints:

1 <= s.length <= 100 1 <= target.length <= 10 s and target consist of lowercase English letters.

carloscn commented 1 year ago

Analysis

pub fn rearrange_characters(s: &str, target: &str) -> i32
{
    let mut ret:i32 = 0;
    if s.is_empty() || target.is_empty() || s.len() < target.len() {
        return ret;
    }

    let mut s_dup:Vec<char> = s.chars().collect();
    let t_dup:Vec<char> = target.chars().collect();
    let mut count_min_number:usize = usize::MAX;
    for i in 0..target.len() {
        let mut j:usize = 0;
        let mut count:usize = 0;
        let mut index:usize = 0;
        while j < s_dup.len() {
            if s_dup[j] == t_dup[i] {
                count += 1;
                index = j;
            }
            j += 1;
        }
        s_dup.remove(index);
        count_min_number = count.min(count_min_number);
    }

    ret = count_min_number as i32;

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170520 https://github.com/carloscn/structstudy/commit/3ba4dc186ebf66849e179b5a701633c4fc313aaf