查找子字符串的位置

题目

查找子字符串的位置

解答

public class FindStr {
    public static void main(String[] args) {
        System.out.println(strStr("source", "target"));
    }

    public static int strStr(String source, String target) {
        // write your code here


        if (source==null||target==null){
            return -1;
        }

        char[] sources = source.toCharArray();

        char[] targets = target.toCharArray();

        if ((sources.length==targets.length)&&(sources.length==0)){
            return 0;
        }
        for (int i = 0; i < sources.length; i++) {
            boolean isExist = true;
            for (int j = 0; j < targets.length; j++) {
                if((i+j)>=sources.length){
                    isExist= false;
                    break;
                }
                if (sources[i+j] != targets[j]) {
                    isExist = false;
                    break;
                }
            }
            if (isExist){
                return i;
            }
        }
        return -1;
    }

}
点赞