티스토리 뷰
Problem
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
Constraints:
- 1 <= s.length <= 10^5
- s consists of only lowercase English letters.
Solution
문자열 s가 주어졌을 때 처음으로 반복되지 않는 문자가 나오는 인덱스를 반환하는 문제입니다.
반복되지 않는지 확인해야하기 때문에 문자열 전체 탐색이 필요합니다.
탐색하면서 각 문자열이 몇 번 나타났는지 카운트하고, 다시 문자열 앞부터 탐색하면서 한 번 나타난 문자를 반환하면 됩니다.
Test
package io.lcalmsky.leetcode.first_unique_character_in_a_string;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
public void givenString_findFirstUniqueCharacter_thenCorrect() {
assertAll(
() -> test("leetcode", 0),
() -> test("loveleetcode", 2),
() -> test("aabb", -1)
);
}
private void test(String given, int expected) {
// when
Solution firstUniqueCharacterInAString = new Solution();
int actual = firstUniqueCharacterInAString.firstUniqChar(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
1338. Reduce Array Size to The Half (0) | 2022.08.19 |
---|---|
804. Unique Morse Code Words (0) | 2022.08.18 |
13. Roman to Integer (0) | 2022.08.13 |
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2022.08.12 |
98. Validate Binary Search Tree (0) | 2022.08.11 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 스프링 데이터 jpa
- Linux
- gRPC
- Spring Boot JPA
- r
- Spring Data JPA
- spring boot app
- JPA
- 스프링 부트 애플리케이션
- spring boot jwt
- 스프링 부트 튜토리얼
- 헥사고날 아키텍처
- 스프링부트
- 스프링 부트 회원 가입
- JSON
- Spring Boot
- Spring Boot Tutorial
- 클린 아키텍처
- 스프링 부트
- @ManyToOne
- 알고리즘
- QueryDSL
- proto3
- Jackson
- leetcode
- 함께 자라기 후기
- 함께 자라기
- spring boot application
- intellij
- Java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함