LeetCode

345. Reverse Vowels of a String

2017-01-12  本文已影响0人  小万叔叔
/** 
 Write a function that takes a string as input and reverse only the vowels of a string.
 
 Example 1:
 Given s = "hello", return "holle".
 
 Example 2:
 Given s = "leetcode", return "leotcede".
 
 Note:
 The vowels does not include the letter "y".
 */
/**
 Thinking:
 A、E、I、O、U 都属于 vowels
 给定两个游标,一个从左,一个从右,左边遇到元音停下来,
 右边开始,右边遇到元音后进行交换,知道左右相遇
 Swift 交换 string 内部字符太低效
 转化为 Array 做交换更合适
*/

func reverseVowels(_ str: String) -> String {
    guard str.unicodeScalars.count > 1 else {
        return str
    }
    
    //是否匹配元音字母
    func matchVowels(_ ch: String) -> Bool {
        let chArray:[String] = ["A", "E", "I", "O", "U"]
        let chLowCaseArray:[String] = ["a", "e", "i", "o", "u"]
        
        if chArray.contains(ch) || chLowCaseArray.contains(ch) {
            return true
        }
        return false
    }
    
    var reverseArray = str.characters.map { String($0) }
    var left: Int = 0
    var right: Int = str.characters.count - 1
    
    //Swift string 内部元素交换,是否有更好的方法?
    func swap(_ left: Int, _ right: Int) {
        let temp = reverseArray[left]
        print("\(reverseArray[left]), \(reverseArray[right])")
        reverseArray[left] = reverseArray[right]
        reverseArray[right] = temp
    }
    
    while left < right {
        let ch = reverseArray[left]
        //如果左边匹配,则进入到右边
        if (matchVowels(ch)) {
            while left < right {
                let chRight = reverseArray[right]
                //如果右边也匹配,则进入交换, 交换完毕,继续左边
                if (matchVowels(chRight)) {
                    swap(left, right)
                    right -= 1
                    break
                }
                right -= 1
            }
        }
        left += 1
    }
      
    return reverseArray.joined()
}

reverseVowels("hell again")
上一篇下一篇

猜你喜欢

热点阅读