-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstUniqueCharacter.php
More file actions
48 lines (46 loc) · 1.18 KB
/
Copy pathFirstUniqueCharacter.php
File metadata and controls
48 lines (46 loc) · 1.18 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;
/**
* First Unique Character in a String
*
* Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
*
* Example 1:
* Input: s = "leetcode" Output: 0
* Example 2:
* Input: s = "loveleetcode" Output: 2
* Example 3:
* Input: s = "aabb" Output: -1
*
* https://leetcode.com/problems/first-unique-character-in-a-string
*/
class FirstUniqueCharacter
{
/**
* @param string $str
* @return int
*/
public function firstUniqChar(string $str): int
{
$strHash = [];
$sWords = str_split($str);
foreach ($sWords as $sWord) {
if (!isset($strHash[$sWord])) {
$strHash[$sWord] = 1;
} else {
$strHash[$sWord]++;
}
}
$firstNonRepeatingWord = '';
foreach ($strHash as $key => $value) {
if ($value === 1) {
$firstNonRepeatingWord = $key;
break;
}
}
if ($firstNonRepeatingWord === '') {
return -1;
}
return (int) strpos($str, $firstNonRepeatingWord);
}
}