13. strStr

Description

For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1.

Analysis


2h of thinking

Code

class Solution {
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        //write your code here
        
        if (source == null || target == null) {
            return -1;
        } 
        if (target == "") {
            return 0;
        }
        if (source == "") {
            return -1;
        }

        int start = 0;
        // 如果剩下的字母不够needle长度就停止遍历
        while(start <= source.length() - target.length()){
            int i1 = start, i2 = 0;
            while(i2 < target.length() && source.charAt(i1) == target.charAt(i2)){
                i1++;
                i2++;
            }
            if(i2 == target.length()) return start;
            start++;
        }

        return -1;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,487评论 0 23
  • 《绿悠游》 竹幽绿柳漫漫守, 车溪木轮渐渐流。 幺妹船头声声秀, 青水鱼蝶仙仙游。 创作诗词2017.06.08 ...
    Amine婉婉阅读 1,787评论 0 1
  • 生活太近……
    曜黑阅读 1,521评论 0 0
  • 五一劳动节放假三天,我终于在老家可以睡懒觉了。 在我耳边只听见爹爹的声音,你个懒虫,起来吃饭了,我真的不想起来,在...
    烧锅的男孩阅读 4,419评论 12 4
  • 我在外婆家度过七岁以前的时光。 外婆家住的是两层的平房,前面就是一条河,周围有菜地,屋后便是大片农田。...
    沈随意啊阅读 1,085评论 0 2