From d642ca2c9afd5d7611164d524e3a23f160e84af4 Mon Sep 17 00:00:00 2001 From: hemant Date: Fri, 2 Oct 2020 10:46:44 +0530 Subject: [PATCH] Adding CPP Implementations --- src/main/java/com/gyanblog/cpp/StrToInt.cpp | 36 +++++++++++++++++++++ src/main/java/com/gyanblog/cpp/strstr.cpp | 20 ++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/main/java/com/gyanblog/cpp/StrToInt.cpp create mode 100644 src/main/java/com/gyanblog/cpp/strstr.cpp diff --git a/src/main/java/com/gyanblog/cpp/StrToInt.cpp b/src/main/java/com/gyanblog/cpp/StrToInt.cpp new file mode 100644 index 0000000..43256e9 --- /dev/null +++ b/src/main/java/com/gyanblog/cpp/StrToInt.cpp @@ -0,0 +1,36 @@ +/* Adding CPP implementation of the problem: https://oj.leetcode.com/problems/string-to-integer-atoi/ */ + +/* +*Implementing function to convert string to an integer. + +*If no valid conversion could be performed, a zero value is returned. + +*If the correct value is out of the range of representable values, the maximum integer value (2147483647) or the minimum integer value (–2147483648) is returned. + +*For more explanation, visit- https://www.gyanblog.com/gyan/coding-interview/leetcode-string-integer-atoi/ +*/ + +class Solution { +public: + int myAtoi(string str) { + int sign=1, i=0; + int maxdiv = INT_MAX/10; + while (str[i]==' ') i++; + if (i'9') + return sign*num; + int digit = str[i]-'0'; + if (num > maxdiv || num==maxdiv && digit>=8) + return sign==1 ? INT_MAX : INT_MIN; + num = num*10 + digit; + i++; + } + return sign*num; + } +}; diff --git a/src/main/java/com/gyanblog/cpp/strstr.cpp b/src/main/java/com/gyanblog/cpp/strstr.cpp new file mode 100644 index 0000000..9bdf38c --- /dev/null +++ b/src/main/java/com/gyanblog/cpp/strstr.cpp @@ -0,0 +1,20 @@ +/* Adding CPP implementation of Problem : https://oj.leetcode.com/problems/implement-strstr/ */ + +/* Assuming n=length of haystack, m=length of needle, then - +O(nm) runtime, O(1) space complexity */ + +/* BRUTE FORCE: Scan the needle with the haystack from its first position and start matching all subsequent letters one by one. +If one of the letters does not match, we start over again with the next position in the haystack. */ + +class Solution { +public: + int strStr(string haystack, string needle) { + for (int i=0; ; i++) { + for (int j=0; ; j++) { + if (j == needle.length()) return i; + if (i+j == haystack.length()) return -1; + if (needle[j] != haystack[i+j]) break; + } + } + } +}; \ No newline at end of file