Journey of LeetCode|DAY 8
Preface
This is a new day to continue my string journey.
Learn something new and keep reviewing what I learnt before.
1. Find the Index of the First Occurrence in a String
LeetCode Link: 28. Find the Index of the First Occurrence in a String
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Analysis and Solution
KMP
LeetCode C++ as followings KMP
class Solution {
public:
void getNext(int* next, const string& s) {//bulid next array
int j = -1;//initial j
next[0] = j;//define next
for(int i = 1; i < s.size(); i++) { // traverse s from 1
while (j >= 0 && s[i] != s[j + 1]) { // when next not matched
j = next[j]; // go back
}
if (s[i] == s[j + 1]) { // matched the same
j++;
}
next[i] = j; // send the length of matched array to next[i]
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {//remove the special situation
return 0;
}
int next[needle.size()];
getNext(next, needle);//apply getNext function and find the next array
int j = -1; // // unified with next array
for (int i = 0; i < haystack.size(); i++) { // traverse haystack from 0
while(j >= 0 && haystack[i] != needle[j + 1]) { // not match
j = next[j]; // go back
}
if (haystack[i] == needle[j + 1]) { // matched; i j go back together
j++; // continue to next one
}
if (j == (needle.size() - 1) ) { // found the needle
return (i - needle.size() + 1);//the first location of the needle
}
}
return -1;
}
};
2. Repeated Substring Pattern
LeetCode Link: 459. Repeated Substring Pattern
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Analysis and Solution
KMP
LeetCode C++ as followings KMP
class Solution {
public:
void getNext (int* next, const string& s){//bulid next array
next[0] = -1;//define next
int j = -1;//initial j
for(int i = 1;i < s.size(); i++){//traverse s from 1
while(j >= 0 && s[i] != s[j + 1]) {// when next not matched
j = next[j];// go back
}
if(s[i] == s[j + 1]) {//matched
j++;
}
next[i] = j;// send the length of matched array to next[i]
}
}
bool repeatedSubstringPattern (string s) {
if (s.size() == 0) {remove the special situation
return false;
}
int next[s.size()];
getNext(next, s);//apply getNext function and find the next array
int len = s.size();
if (next[len - 1] != -1 && len % (len - (next[len - 1] + 1)) == 0) {//got repeatedSubstring
return true;
}
return false;
}
};