티스토리 뷰
광고
광고
Problem
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
Constraints:
- 0 <= s.length <= 1000
- t.length == s.length + 1
- s and t consist of lowercase English letters.
Solution
문자열 s와 t가 주어지고 t는 s를 랜덤으로 섞은 문자에 하나의 다른 문자를 추가한 문자입니다.
t에 추가된 문자를 반환하는 문제입니다.
public class Solution {
public char findTheDifference(String s, String t) {
int[] alphabets = new int[26];
for (char c : s.toCharArray()) { // (1) s 문자열을 탐색하면서 각 문자의 개수를 더해줍니다.
alphabets[c - 'a']++;
}
for (char c : t.toCharArray()) { // (2) t 문자열을 탐색하면서 각 문자의 개수를 빼주다가 -1이 되면 해당 문자를 반환합니다.
alphabets[c - 'a']--;
if (alphabets[c - 'a'] < 0) {
return c;
}
}
throw new IllegalStateException();
}
}
- s 문자열을 탐색하면서 각 문자의 개수를 더해줍니다.
- t 문자열을 탐색하면서 각 문자의 개수를 빼주다가 -1이 되면 해당 문자를 반환합니다.
Test
package io.lcalmsky.leetcode.find_the_difference;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertSame;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void testAll() {
assertAll(
() -> test("abcd", "abcde", 'e'),
() -> test("", "y", 'y')
);
}
private void test(String s, String t, char expected) {
// when
Solution solution = new Solution();
char actual = solution.findTheDifference(s, t);
// then
assertSame(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
525. Contiguous Array (0) | 2022.02.16 |
---|---|
258. Add Digits (0) | 2022.02.15 |
80. Remove Duplicates from Sorted Array II (0) | 2022.02.13 |
438. Find All Anagrams in a String (0) | 2022.02.07 |
121. Best Time to Buy and Sell Stock (0) | 2022.02.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Spring Boot
- Java
- Linux
- intellij
- 헥사고날 아키텍처
- proto3
- spring boot jwt
- JPA
- 스프링 부트
- 스프링 데이터 jpa
- 알고리즘
- spring boot app
- Spring Boot JPA
- gRPC
- Spring Data JPA
- spring boot application
- r
- QueryDSL
- @ManyToOne
- 함께 자라기 후기
- 스프링부트
- Jackson
- Spring Boot Tutorial
- leetcode
- 스프링 부트 애플리케이션
- 클린 아키텍처
- 함께 자라기
- 스프링 부트 회원 가입
- JSON
- 스프링 부트 튜토리얼
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함