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

    一、题目

      1、审题

        

      2、分析

        返回第二个字符串在第一个字符串内出现的下标,否则返回 -1。

    二、解答

      1、思路:

        a、遍历第一个字符串中的字符;

        b、若出现与第二个字符串的首个字符相同,则第二层循环,遍历第二个字符串,依次比较与第一个字符串的每一个字符;

        c、若每一个字符相等,则返回下标,否则,跳出 b 继续 a 的遍历public class Solution {

    public int strStr(String haystack, String needle) {
            
            
            int len1 = haystack.length();
            int len2 = needle.length();
            if(len2 == 0) return 0;
            if(len1 < len2)    return -1;
            
            for (int i = 0; i <= len1-len2; i++) {
    if(haystack.charAt(i) == needle.charAt(0)) { int j = 1; for(; j < len2; j++) { if(haystack.charAt(i+j) != needle.charAt(j)) { break; } } if(j == len2) return i; } } return -1; } }

      实现二:

    public int strStr(String haystack, String needle) {
            
            
            if(needle.length() == 0)    return 0;
            for (int i = 0; i <= haystack.length() - needle.length(); i++) 
                for(int j = 0; j < needle.length() && haystack.charAt(i+j) == needle.charAt(j); j++)
                    if(j == needle.length()-1) return i;
                    
            return -1;
        
        }
  • 相关阅读:
    Solved:Spring Junit Test NoSuchMethodError
    Stack实现
    CLRS10.2-8练习
    CLRS10.2-7练习
    CLRS10.2-4练习
    CLRS10.1-7练习
    CLRS10.1-6练习
    算法:吸血鬼数字算法
    CLRS最大子数组问题
    VS快捷键
  • 原文地址:https://www.cnblogs.com/skillking/p/9428269.html
Copyright © 2011-2022 走看看