欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

子字符串下标查找

程序员文章站 2022-03-21 21:34:38
...

1、题目描述

子字符串下标查找2、java版AC代码

 public int strStr(String haystack, String needle) {
         if(needle.isEmpty()){
            return 0;
        }
        int i = 0,j=0,index=-1;
        while(i < haystack.length() && j < needle.length()) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                if(index == -1){
                    index = i;
                }
                i++;
                j++;
            } else {
                if(index != -1){
                    i=index+1;
                }else{
                    i++;
                }
                index = -1;
                j = 0;
            }
        }
        if(j==needle.length()){
            return index;
        }
        return -1;
    }

3、swift版AC代码(swift4语法)

func strStr(_ haystack: String, _ needle: String) -> Int {
         if needle.isEmpty {
        return 0
    }
    if haystack.count < needle.count {
        return -1
    }
    let cishu = haystack.count - needle.count + 1
    var i = 0
    while i < cishu {
        let startIndex = haystack.index(haystack.startIndex, offsetBy: i)
        let endIndex = haystack.index(haystack.startIndex, offsetBy: i+needle.count)
        let tmp = haystack[startIndex..<endIndex]
        if tmp == needle {
            return i
        }
        i+=1
    }
    return -1
    }