g2301_2400.s2351_first_letter_to_appear_twice.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2301_2400.s2351_first_letter_to_appear_twice;
// #Easy #String #Hash_Table #Counting #2022_08_14_Time_0_ms_(100.00%)_Space_42.3_MB_(29.00%)
/**
* 2351 - First Letter to Appear Twice\.
*
* Easy
*
* Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.
*
* **Note**:
*
* * A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
* * `s` will contain at least one letter that appears twice.
*
* **Example 1:**
*
* **Input:** s = "abccbaacz"
*
* **Output:** "c"
*
* **Explanation:**
*
* The letter 'a' appears on the indexes 0, 5 and 6.
*
* The letter 'b' appears on the indexes 1 and 4.
*
* The letter 'c' appears on the indexes 2, 3 and 7.
*
* The letter 'z' appears on the index 8.
*
* The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
*
* **Example 2:**
*
* **Input:** s = "abcdd"
*
* **Output:** "d"
*
* **Explanation:**
*
* The only letter that appears twice is 'd' so we return 'd'.
*
* **Constraints:**
*
* * `2 <= s.length <= 100`
* * `s` consists of lowercase English letters.
* * `s` has at least one repeated letter.
**/
public class Solution {
public char repeatedCharacter(String s) {
int n = s.length();
int[] hm = new int[26];
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
hm[c - 'a']++;
if (hm[c - 'a'] > 1) {
return c;
}
}
return '0';
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy