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;
    
    }

 

posted @ 2018-08-06 08:34  skillking2  阅读(96)  评论(0编辑  收藏  举报