LoginSignup
3
5

More than 5 years have passed since last update.

面接で絶対に押さえておきたいアルゴリズム問題(5)

Last updated at Posted at 2017-07-03

問題:Common Prefix

PrefixとはStringの冒頭につける文字列で、例えば、
"undecided" と"unchange"の Prefixは "un"である。

今回の問題は、Stringの配列から、String同士でマッチする、一番長いPrefixを見つけ出して返す。

例:

input: ["flower", "flour", "flappecino"]
return: "flo"

input ["flower", "garbage", "onion"]
return: ""

ヒント:

解答:


func longestCommonPrefix(_ strs: [String]) -> String {

    var storedPrefix = ""
    var commonPrefix = ""
    let array = strs

    for (index, word) in array.enumerated() {

        for (indexTwo, wordTwo) in array.enumerated(){
            if index != indexTwo {

                let arrayA = Array(word.characters)
                let arrayB = Array(wordTwo.characters)

                if word == "" || wordTwo == ""{
                    break
                }

                for (index,a) in arrayA.enumerated(){

                    if a == arrayB[index] {
                        commonPrefix.insert(a, at: commonPrefix.endIndex)
                    }

                    if a != arrayB[index] {
                        break
                    }

                }


                if commonPrefix.characters.count > storedPrefix.characters.count {
                    storedPrefix = commonPrefix
                }

                commonPrefix = ""

                print(storedPrefix)

            }

        }

    }

    return storedPrefix
}

メモ / ポイント

一応解きましたが、ループを回しすぎているので、もっといい解決方法があるはず・・・!

メモ / ポイント

3
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5