美文网首页
13. strStr

13. strStr

作者: MoveOnLC | 来源:发表于2016-10-04 23:22 被阅读0次

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

    相关文章

      网友评论

          本文标题:13. strStr

          本文链接:https://www.haomeiwen.com/subject/msjsyttx.html