Last active
July 2, 2021 18:11
-
-
Save lebeerman/d10cb555cd2c27609e3181cd8e19ea3e to your computer and use it in GitHub Desktop.
team Activity - Strstr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First pass at writing C++... also probably should have checked the docs for some native find/includes/etc methods, | |
// but there's something kinda fun about brute forcing a solution first... | |
// TODO: other early return cases? string methods to use instead? ew nested loop... | |
class Solution { | |
public: | |
int strStr(string haystack, string needle) { | |
if (needle == "") { | |
return 0; | |
} else if (needle.length() > haystack.length()){ | |
return -1; | |
} else { | |
return needleCheck(haystack, needle); | |
} | |
} | |
int needleCheck(string haystack, string needle) { | |
for (int i = 0; i < haystack.length(); i++) { | |
if (haystack[i] == needle[0]) { | |
// do some additional checks if there's character matches... | |
// ew - feels like there's a recursive or less nested way... | |
// or a curried approach? | |
bool found = true; | |
for(int j = 0; j < needle.length(); j++) { | |
if (haystack[i+j] != needle[j]) { | |
found = false; | |
break; | |
} | |
} | |
if (found) { | |
return i; | |
} | |
} | |
} | |
return -1; | |
} | |
}; | |
# --- Found on submissions --- | |
# (ya gotta have an account and click into the time distribution) https://leetcode.com/submissions/detail/516402722/ | |
# 0 ms submission | |
class Solution { | |
public: | |
int strStr(string haystack, string needle) { | |
if (needle == "") { | |
return 0; | |
} | |
// ah... .size() - | |
if (haystack.size() < needle.size()) { | |
return -1; | |
} | |
if (haystack.size() == needle.size()) { | |
if (haystack == needle) { | |
return 0; | |
} else { | |
return -1; | |
} | |
} | |
size_t pos = haystack.find(needle); | |
if (pos != string::npos) { | |
return pos; | |
} else { | |
return -1; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment