Swift solution - Two Pointers


  • 0
    class Solution {
        func findLongestWord(_ s: String, _ d: [String]) -> String {
            let chars = Array(s.characters)
            var longestWord = ""
            var i = 0
            
            for dictWord in d {
                i = 0
                let dictWordChars = Array(dictWord.characters)
                for char in chars {
                    if i < dictWordChars.count && char == dictWordChars[i] {
                        i += 1
                    }
                }
                if i == dictWordChars.count && dictWordChars.count >= longestWord.characters.count {
                    if dictWordChars.count > longestWord.characters.count || dictWord.compare(longestWord) == .orderedAscending {
                        longestWord = dictWord
                    }
                }
            }
            
            return longestWord
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.