티스토리 뷰

Algorithm/LeetCode

389. Find the Difference

Jaime.Lee 2022. 2. 14. 10:30

소스 코드는 여기 있습니다.
문제는 여기 있습니다.

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();
  }
}
  1. s 문자열을 탐색하면서 각 문자의 개수를 더해줍니다.
  2. 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
댓글