LeetCode-探索-初级算法-字符串-7. 实现 strStr()(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-字符串-7. 实现 strStr()(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 实现 strStr()
  • 语言:java

  • 思路:…无话可说

  • 代码(0ms):

    class Solution {
        public int strStr(String haystack, String needle) {
            return haystack.indexOf(needle);
        }
    }
    
  • 参考代码(1ms):

    class Solution {
        public int strStr(String haystack, String needle) {
        	//当needle为空则返回0
    		if(needle.equals(""))
    			return 0;
    		
    		int len = needle.length();
    	//查看haystack字符串是否包含有needle字符串
    		for(int i=0; i<haystack.length()-len+1;i++) {
    			if(haystack.substring(i, i+len).equals(needle)) {
    				return i;
    			}
    		}
            return -1;
        }
    }
    
  • 重写(1ms):

    class Solution {
        public int strStr(String haystack, String needle) {
            int len2 = needle.length();
            if(len2==0)
                return 0;
            int len1 = haystack.length();
            for(int i = 0; i < len1-len2+1; ++i){
                if(haystack.substring(i,i+len2).equals(needle))
                    return i;
            }
            return -1;
        }
    }
    

你可能感兴趣的:(LeetCode,非讲解,原创)