2024. 10. 8. 11:55ㆍ알고리즘/Leetcode
Solution
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Examples
Example 1:
Input: s = "leetcode"
Output: 0
Explanation: The character 'l' at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Explanation
class Solution {
public int firstUniqChar(String s) {
int[] charArr = new int[26];
for(int i = 0; i < s.length(); i++)
charArr[s.charAt(i) - 'a']++;
for(int i = 0; i < s.length(); i++){
if(charArr[s.charAt(i) - 'a'] == 1)
return i;
}
return -1;
}
}
The array, charArr, is created with the size 26, where each index corresponds to a letter in the alphabet and it is to store the frequency of each character.
First Loop: Counting Character Frequencies
This loop iterates through the entire String s and each time a character is encountered, its corresponding position in the charArr array is incremented. This way, we can track how many times each character appears in the string.
Second Loop: Finding the First Non-Repeating Character
In this loop, we iterate over the string s again and for each character in the string, we check if its frequency in the charArr array is 1. If so, that means this character appears only once in the string, making it a non-repeating character and then the index i of this character is returned as the result. Otherwise, return -1 as the result.
'알고리즘 > Leetcode' 카테고리의 다른 글
| Valid Palindrome (2) | 2024.10.11 |
|---|---|
| Valid Anagram (0) | 2024.10.10 |
| Reverse Integer (0) | 2024.10.07 |
| Reverse String (0) | 2024.10.06 |
| Valid Sudoku (2) | 2024.10.04 |