Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input:haystack = "hello", neddle = "ll"
Output:2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().python
给定一个haystack字符串和一个needle字符串,须要咱们作的是在haystack字符串中找出needle字符串出现的第一个位置(从0开始),若是不存在返回-1。此外,若是needle字符串为空,返回0。函数
咱们想到将needle字符串视为haystack字符串的一个子串,利用substr(pos, n)函数返回haystack字符串中从pos到pos+n位置的字符串,检验返回的字符串与needle是否一致,若是一致则返回pos,不然返回-1。这里的pos应该是needle字符串第一个字符在haysatck字符串中的位置,n应该是needle字符串的长度。优化
这里咱们要注意的是遍历次数(循环次数),由于是在haystack字符串中找needle字符串,那么循环次数必定不会超过haystack.size() - needle.size(),超过这个次数,说明needle确定不存在。this
语法:bool empty()
若是字符串为空,返回true;不然返回false。code
语法:basic_string substr(size_type index, size_type num = npos)
substr返回字符串的一个子串,从index开始,到index+num结束,子串长度为num。若是没有指定num,则默认值是string::npos,这样substr()返回从index开始的剩余字符串。ip
class Solution { public: int strStr(string haystack, string needle) { //先考虑特殊状况 //特殊状况1:needle字符为空 if(needle.empty()) return 0; //特殊状况2:needle字符长度大于haystack字符长度或者haystack字符长度为0 if(needle.size() > haystack.size() || haystack.empty() ) return -1; for(int i=0;i<haystack.size() - needle.size() + 1;i++){ if(haystack[i] == needle[0] && haystack.substr(i, needle.size()) == needle ) return i; } return -1; } };