본문 바로가기

BOJ알고리즘

BOJ 10809 with Swift

반응형

BOJ 10809 with Swift

10809번: 알파벳 찾기

문제

  • 알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.

입력값

  • 첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.

출력값

  • 각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.
  • 만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.

코드

import Foundation

struct Q10809 {
    static let alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    static var arr = [Int].init(repeating: -1, count: alpha.count)
    static func main(){
        if let str = readLine() {
            for char in str {
                guard let charIndex = str.index(of: char) else { break }
                let strIndex = str.distance(from: str.startIndex, to: charIndex)
                if let index = alpha.index(of: String(char)){
                    if arr[index] == -1 {
                        arr[index] = strIndex
                    }
                }
            }
        }
        // Array 를 newLine 하지 않고 print 하는 방법
        for a in arr {
            print(a, separator: "", terminator: " ")
        }
    }
}

Q10809.main()
반응형

'BOJ알고리즘' 카테고리의 다른 글

BOJ 1157 with Swift  (0) 2018.09.10
BOJ 11654 with Swift  (0) 2018.09.02
BOJ 10039 with Swift  (0) 2018.09.02
BOJ 8958 with Swift  (0) 2018.09.02
BOJ 2920 with Swift  (0) 2018.09.02