leetcode
leetcode 2451 ~ 2500
最长相邻不相等子序列 I

最长相邻不相等子序列 I

难度:

标签:

题目描述

You are given a string array words and a binary array groups both of length n, where words[i] is associated with groups[i].

Your task is to select the longest alternating subsequence from words. A subsequence of words is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary array groups differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in the groups array.

Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1] denoted as [i0, i1, ..., ik-1], such that groups[ij] != groups[ij+1] for each 0 <= j < k - 1 and then find the words corresponding to these indices.

Return the selected subsequence. If there are multiple answers, return any of them.

Note: The elements in words are distinct.

 

Example 1:

Input: words = ["e","a","b"], groups = [0,0,1]

Output: ["e","b"]

Explanation: A subsequence that can be selected is ["e","b"] because groups[0] != groups[2]. Another subsequence that can be selected is ["a","b"] because groups[1] != groups[2]. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is 2.

Example 2:

Input: words = ["a","b","c","d"], groups = [1,0,1,1]

Output: ["a","b","c"]

Explanation: A subsequence that can be selected is ["a","b","c"] because groups[0] != groups[1] and groups[1] != groups[2]. Another subsequence that can be selected is ["a","b","d"] because groups[0] != groups[1] and groups[1] != groups[3]. It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3.

 

Constraints:

  • 1 <= n == words.length == groups.length <= 100
  • 1 <= words[i].length <= 10
  • groups[i] is either 0 or 1.
  • words consists of distinct strings.
  • words[i] consists of lowercase English letters.

代码结果

运行时间: 25 ms, 内存: 15.9 MB


/* 
思路:
1. 使用Stream API处理数组,初始思路与传统Java方法类似。
2. 遍历数组 words 和 groups,通过条件过滤和收集处理符合条件的子序列。
3. 返回最长的子序列。
*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SolutionStream {
    public static List<String> longestSubsequence(String[] words, int[] groups) {
        return IntStream.range(0, words.length)
                .mapToObj(i -> IntStream.range(i, words.length)
                        .filter(j -> j == i || groups[j] != groups[j - 1])
                        .mapToObj(j -> words[j])
                        .collect(Collectors.toList()))
                .max((list1, list2) -> list1.size() - list2.size())
                .orElse(new ArrayList<>());
    }

    public static void main(String[] args) {
        String[] words = {"e", "a", "b"};
        int[] groups = {0, 0, 1};
        System.out.println(longestSubsequence(words, groups)); // 输出: ["e", "b"]
    }
}

解释

方法:

该题解的核心思路是遍历groups数组,并构建一个索引列表arr,用于记录符合条件的words的索引。初始时,arr包含第一个元素的索引0,表示至少包含words的第一个元素。之后,遍历groups数组,只要当前元素与arr列表中最后一个记录的索引对应的groups值不同,就将当前索引添加到arr中。这样,arr中存储的索引对应的groups值必然是交替变化的,满足题目要求的连续不相等条件。最终,根据arr中的索引,提取words数组中对应的字符串,形成所求的最长子序列。

时间复杂度:

O(n)

空间复杂度:

O(n)

代码细节讲解

🦆
在遍历groups数组时,你是如何确定从第一个元素的索引0开始的?这一决定是否总是有效,例如在groups数组为空的情况下如何处理?
从第一个元素的索引0开始是基于这样一个前提:至少要包含一个元素以构建子序列。这个决定在groups非空时是有效的,因为至少有一个元素可以开始构建序列。然而,如果groups数组为空,则这一策略将失效,因为不存在任何元素可以被加入到索引列表arr中。在这种情况下,算法应该首先检查groups是否为空,如果为空,则直接返回一个空的words子序列。
🦆
题解中提到,如果groups数组中的值完全交替,arr可以存储所有n个索引。那么如果groups数组中存在连续的相同值,这种情况下算法的表现如何?
如果groups数组中存在连续的相同值,算法将跳过这些连续相同的值,只在值变化时添加索引到arr中。这意味着arr将不会包含所有索引,而只包含那些对应于groups值变化点的索引。这种处理方式确保了构建的子序列满足相邻不相等的条件,同时尽可能地长。
🦆
在函数getLongestSubsequence中,为什么选择使用enumerate来遍历groups数组,而不是简单的for循环遍历索引?这里使用enumerate的具体优势是什么?
在函数中使用enumerate来遍历groups数组可以同时获得元素的索引和值,这使得代码更为简洁和直观。使用enumerate避免了需要手动处理索引,如在传统for循环中需要使用range(len(groups))。这种方法提高了代码的可读性和减少了出错的可能性,因为它直接提供了每个元素的索引和对应的值。
🦆
由于题目说明words中的元素是不同的,这是否影响了算法的设计?如果words中存在相同的元素,这个算法还适用吗?
题目说明words中的元素是不同的,这简化了算法设计,因为不需要考虑去重或处理相同元素带来的复杂性。如果words中存在相同的元素,该算法依然适用,因为算法主要依赖于groups数组来确定哪些words元素应该被选取。只要groups数组的处理逻辑不变,即使words中有重复元素,也可以正确地根据groups数组构建符合条件的子序列。

相关问题