LeetCode (389) - Find the Difference

Seong Oh·2022년 2월 7일

하단 Title 클릭 시 해당 문제 페이지로 이동합니다.

- Find the Difference

  • Acceptance: 60.1%
  • Difficulty : Easy

문제 설명

String s와 한 문자가 더 추가된 Stringt가 주어진다. 추가된 문자를 return.

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lowercase English letters.

예시 1

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

예시 2

Input: s = "", t = "y"
Output: "y"

문제 풀이

  • 각 문자는 ascii code 값을 갖고 있다.
  • char results의 문자 값은 빼고 t의 문자 값은 더하면 추가된 문자를 찾을 수 있다.

코드

class Solution {
    public char findTheDifference(String s, String t) {
        char result = 0;

        for (int i = 0, sLength = s.length(); i < sLength; i++) {
            result -= s.charAt(i);
            result += t.charAt(i);
        }

        result += t.charAt(t.length() - 1);

        return result;
    }
}

0개의 댓글