当前位置:网站首页>String implementation strstr()

String implementation strstr()

2022-06-25 10:06:00 Morris_

LC Realization strStr()

swift The code is as follows :

class ViewController: UIViewController {
    

    override func viewDidLoad() {
    
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
        print(strStr("hello", "ll"))
        print(strStr("aaaaa", "bba"))

    }
    
    func strStr(_ haystack: String, _ needle: String) -> Int {
    
        
        if needle.isEmpty {
    
            return 0
        }
        
        let array1 = Array(haystack)
        let array2 = Array(needle)
        
        var i = 0
        while (i + array2.count) <= array1.count {
    
            
            let temp: Array = Array(array1[i...i + array2.count - 1])
            
            if temp == array2 {
    
                return i
            }
            
            i += 1
        }
        
        return -1
    }

}

Ideas :

Move the pointer to the right , contrast
 Please add a picture description

原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250915051808.html