-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestSubsequenceOfDistinctCharacters.php
More file actions
48 lines (43 loc) · 1.13 KB
/
Copy pathSmallestSubsequenceOfDistinctCharacters.php
File metadata and controls
48 lines (43 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
namespace App;
/**
* Smallest Subsequence of Distinct Characters
*
* Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters
* of s exactly once.
*
* Example 1:
* Input: s = "bcabc"
* Output: "abc"
*
* Example 2:
* Input: s = "cbacdcbc"
* Output: "acdb"
*
* https://leetcode.com/problems/smallest-subsequence-of-distinct-characters
*/
class SmallestSubsequenceOfDistinctCharacters
{
/**
* @param string $str
* @return string
*/
public function smallestSubsequence(string $str): string
{
$dict = [];
for ($i = 0, $iMax = strlen($str); $i < $iMax; $i++) {
$dict[$str[$i]] = $i;
}
$stack = [];
for ($i = 0, $iMax = strlen($str); $i < $iMax; $i++) {
$j = $str[$i];
if (!in_array($j, $stack, true)) {
while (!empty($stack) && $stack[count($stack) - 1] > $j && $dict[$stack[count($stack) - 1]] > $i) {
array_pop($stack);
}
$stack[] = $j;
}
}
return implode("", $stack);
}
}