[Swift] String에서 특정 Character count

Kang Hee Young·2022년 2월 7일
0

Swift String에서 특정 Character Count 구하기

Swift String은 구리다.

Swift String에서 filter를 사용해서 특정 캐릭터의 수를 세어보자.

leetcode 389.Find the Difference

string에 filter를 사용해서 Character와 동일한 배열의 count를 구하면 된다.

예시 코드

// Qustion.
// 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.


class Solution {
    func findTheDifference(_ s: String, _ t: String) -> Character {
        for c in t {
            if s.filter({ $0 == c }).count != t.filter({ $0  == c }).count {
                return c
            }
        }
        // default value
        return Character("a")
    }
}
profile
hekang in 42Seoul.

0개의 댓글