0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #833: Find And Replace in String

0
Posted at
func findReplaceString(_ S: String, _ indexes: [Int], _ sources: [String], _ targets: [String]) -> String {
    var answer = [Character]()
    var str = Array(S)
    var  index = 0
    var i = 0
    let offsets = indexes.enumerated().sorted(by: {$0.element < $1.element}).map {$0.offset}
    let indexes = offsets.map {indexes[$0]}
    let sources = offsets.map {sources[$0]}
    let targets = offsets.map {targets[$0]}
    
    while i < str.count {
        if index >= indexes.count {
            answer += Array(str[i...])
            break
        }
        if i == indexes[index] {
            if str.count - indexes[index] < sources[index].count {
                index += 1
                continue
            }
            var possible = true
            for j in stride(from: 0, to: sources[index].count, by: 1) {
                if str[i+j] != Array(sources[index])[j] {
                    possible = false
                    break
                }
            }
            if possible {
                answer.append(contentsOf:Array(targets[index]))
                i += sources[index].count
            }
            index += 1
        } else {
            answer.append(str[i])
            i += 1
        }
    }
    return String(answer)
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?