zoukankan      html  css  js  c++  java
  • Leecode no.28 实现 strStr()

    package com.example.demo.leecode;

    /**
    * 实现 strStr() 函数。
    * @Date 2020/12/29
    * @author Tang
    * 给定一个 haystack 字符串和一个 needle 字符串,
    * 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。
    *
    */
    public class ImplementStrstr {

    private char[] charArray;
    private char[] needleArray;

    public int execute(String haystack, String needle){
    if(haystack == null || needle == null){
    return -1;
    }
    if(haystack.equals(needle)){
    return 0;
    }
    charArray = haystack.toCharArray();
    needleArray = needle.toCharArray();
    //各种判断,恶心
    if(needleArray.length == 0){
    return 0;
    }
    if(charArray.length == 0 || charArray.length < needleArray.length){
    return -1;
    }

    for(int i = 0; i < charArray.length; i++){
    if(charArray[i] == needleArray[0] && ifOccurrence(i)){
    return i;
    }
    }
    return -1;
    }

    //判断charArray从Index位置开始,是否完全包含needleArray
    private boolean ifOccurrence(int index){
    int j = 0;
    while(j < needleArray.length && index < charArray.length){
    if(needleArray[j] != charArray[index]){
    return false;
    }
    j++;
    index++;
    }
    return j == needleArray.length;
    }

    public static void main(String[] args) {
    String charArray = "mississippi";
    String needleArray = "issippi";
    int execute = new ImplementStrstr().execute(charArray, needleArray);
    System.out.println(execute);

    //还有一种简单解法
    int i = charArray.indexOf(needleArray);
    //。。。。
    }

    }
  • 相关阅读:
    解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG
    pywin32安装教程
    Python 3.7 安装Twisted
    富文本编辑器 kindeditor
    git push命令
    git commit命令
    git取别名配置
    kubeadm部署kubernetes v1.14.1高可用集群
    使用Operator部署Prometheus监控k8s集群
    Kickstart批量安装centos7
  • 原文地址:https://www.cnblogs.com/ttaall/p/14207426.html
Copyright © 2011-2022 走看看