@@ -53,30 +53,82 @@ It can be shown that the length of the longest subsequence of indices that satis
53
53
54
54
## Solutions
55
55
56
+ ** Solution 1: Greedy**
57
+
58
+ We can traverse the array $groups$, and for the current index $i$, if $i=0$ or $groups[ i] \neq groups[ i - 1] $, we add $words[ i] $ to the answer array.
59
+
60
+ The time complexity is $O(n)$, where $n$ is the length of the array $groups$. The space complexity is $O(n)$.
61
+
56
62
<!-- tabs:start -->
57
63
58
64
### ** Python3**
59
65
60
66
``` python
61
-
67
+ class Solution :
68
+ def getWordsInLongestSubsequence (
69
+ self , n : int , words : List[str ], groups : List[int ]
70
+ ) -> List[str ]:
71
+ return [words[i] for i, x in enumerate (groups) if i == 0 or x != groups[i - 1 ]]
62
72
```
63
73
64
74
### ** Java**
65
75
66
76
``` java
67
-
77
+ class Solution {
78
+ public List<String > getWordsInLongestSubsequence (int n , String [] words , int [] groups ) {
79
+ List<String > ans = new ArrayList<> ();
80
+ for (int i = 0 ; i < n; ++ i) {
81
+ if (i == 0 || groups[i] != groups[i - 1 ]) {
82
+ ans. add(words[i]);
83
+ }
84
+ }
85
+ return ans;
86
+ }
87
+ }
68
88
```
69
89
70
90
### ** C++**
71
91
72
92
``` cpp
73
-
93
+ class Solution {
94
+ public:
95
+ vector<string > getWordsInLongestSubsequence(int n, vector<string >& words, vector<int >& groups) {
96
+ vector<string > ans;
97
+ for (int i = 0; i < n; ++i) {
98
+ if (i == 0 || groups[ i] != groups[ i - 1] ) {
99
+ ans.emplace_back(words[ i] );
100
+ }
101
+ }
102
+ return ans;
103
+ }
104
+ };
74
105
```
75
106
76
107
### **Go**
77
108
78
109
```go
110
+ func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) {
111
+ for i, x := range groups {
112
+ if i == 0 || x != groups[i-1] {
113
+ ans = append(ans, words[i])
114
+ }
115
+ }
116
+ return
117
+ }
118
+ ```
79
119
120
+ ### ** TypeScript**
121
+
122
+ ``` ts
123
+ function getWordsInLongestSubsequence(n : number , words : string [], groups : number []): string [] {
124
+ const ans: string [] = [];
125
+ for (let i = 0 ; i < n ; ++ i ) {
126
+ if (i === 0 || groups [i ] !== groups [i - 1 ]) {
127
+ ans .push (words [i ]);
128
+ }
129
+ }
130
+ return ans ;
131
+ }
80
132
```
81
133
82
134
### ** ...**
0 commit comments