码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 28. 实现strStr()

时间:2018-10-06 00:04:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:har   图片   style   class   opened   bool   while   splay   none   

技术分享图片
class Solution {
    public int strStr(String haystack, String needle) {
        int i = 0, j = 0;
        int a = haystack.length();
        int b = needle.length();
        if(a<b) return -1;
        else if(b==0 || haystack.equals(needle)) return 0;
        else {
            while(i < a && j < b) {
                if(needle.charAt(j) != haystack.charAt(i)) {
                    i=i-j+1;
                    j=0;
                }
                else {
                    i++;
                    j++;
                }
            }
            if(j==b) return i-j;
            else return -1;
        }
    }
}
双指针

 

 

技术分享图片
class Solution {
    public int strStr(String haystack, String needle) {
                if(haystack.length() == 0&&needle.length() != 0) return -1;
                int l1=haystack.length();
                int l2=needle.length();
                boolean flag;
                for(int i = 0 ; i <= l1-l2; i++){
                    flag = true;
                    for(int j = 0 ; j < needle.length() ; j ++) {
                        if(haystack.charAt(i+j) != needle.charAt(j)) {
                            flag = false;
                            break;
                        }
                    }
                    if(flag) return i;
                }
                return -1;
            }
    }
简洁

 

leetcode 28. 实现strStr()

标签:har   图片   style   class   opened   bool   while   splay   none   

原文地址:https://www.cnblogs.com/Roni-i/p/9746350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!