modalsoul’s blog

これは“失敗”と呼べるかもしれないが、ぼくは“学習体験”と呼びたい

LeetCode 14. Longest Common Prefix

LeetCode Problem No.14.

No.13 is here.

modalsoul.hatenablog.com

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Example 1

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

Code

object Solution {
    def longestCommonPrefix(strs: Array[String]): String = {
        def run(targets:Array[String], acc:String): String = {
            if(!targets.head.isEmpty && targets.tail.forall{ x => !x.isEmpty && x.head == targets.head.head }) 
                run(targets.map(_.tail), acc+targets.head.head)
            else acc
        }
        run(strs, "")
    }
}

Methods

Compare n-th character in each strs.

  • All n-th character are same, accumulate n-th character and increment n.
  • All n-th character are not same, return accumulated characters.

Results

Runtime: 679 ms, faster than 72.08% of Scala online submissions for Longest Common Prefix. Memory Usage: 71.8 MB, less than 11.69% of Scala online submissions for Longest Common Prefix.