zoukankan      html  css  js  c++  java
  • 实现 strStr()

    此博客链接:

    实现 strStr()

    题目链接:https://leetcode-cn.com/leetbook/read/array-and-string/cm5e2/

    题目

    实现 strStr() 函数。

    给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

    说明:

    当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

    对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

    示例 1:

    输入:haystack = "hello", needle = "ll"
    输出:2
    示例 2:

    输入:haystack = "aaaaa", needle = "bba"
    输出:-1
    示例 3:

    输入:haystack = "", needle = ""
    输出:0
     

    提示:

    0 <= haystack.length, needle.length <= 5 * 104
    haystack 和 needle 仅由小写英文字符组成

    题解

    把haystack转换成字符数组hay,取needle中的第一个字符first,在hay字符数组中找first,如果找到,返回hay的下标,如果没有找到返回-1.

    代码

    class Solution {
        public int strStr(String haystack, String needle) {
           char first=needle.charAt(0);
           if(needle.equals("")){
               return 0;
           }
           for(int i=0;i<haystack.length();i++)
           {
               if(haystack.charAt(i)==first){
                   return i;
               }
           }
           return -1;
        }
    }

    结果

    我已经对needle做了特殊处理,但是还是说字符串越界

    出来混总是要还的
  • 相关阅读:
    hdu 2546 饭卡
    poj 2262 Goldbach's Conjecture
    poj 1287 Networking
    poj 2377 Bad Cowtractors
    poj 1789 Truck History
    poj 2349 Arctic Network
    poj 1258 Agri-Net
    acdream 20140730 D题
    hdu 1012 素数判定
    hdu 2098 分拆素数和
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/14926739.html
Copyright © 2011-2022 走看看