zoukankan      html  css  js  c++  java
  • Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    字符串匹配问题,要注意needle 为空的情况,最简单的代码是:

    public class Solution {
        public int strStr(String haystack, String needle) {
            return haystack.indexOf(needle);
        }
    }

    当然这样写就没啥意义了。

    完整代码:

    public class Solution {
        public int strStr(String haystack, String needle) {
            int size1 = haystack.length();
            int size2 = needle.length();
            if(size2==0) return 0;
            int gap = size1-size2;
            for(int i=0;i<=gap;i++) {
                for(int j=0;j<size2;j++) {
                    if(haystack.charAt(j+i)!=needle.charAt(j)) break;
                    else if(j==size2-1) return i;
                }
            }
            return -1;
        }
    }
  • 相关阅读:
    Redis详解(一)——RDB
    十、行锁
    go 上下文context
    go log
    go 结构体取代类
    go select
    go channel
    go 协程(Goroutine)
    go 学习之fmt包
    go 学习之bufio
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4267322.html
Copyright © 2011-2022 走看看