diff --git a/decode-ways/hwi-middle.cpp b/decode-ways/hwi-middle.cpp new file mode 100644 index 000000000..2152eb51b --- /dev/null +++ b/decode-ways/hwi-middle.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int numDecodings(string s) { + int d[101]; + int len = s.size(); + + if (s[0] == '0') // 0으로 시작할 수 없음 + { + return 0; + } + + d[0] = 1; // 빈 문자열 -> 1가지 방법 + d[1] = 1; // 첫 문자 -> 1가지 방법 (0이 아닌건 확인했음) + + for (int i = 2; i <= len; ++i) + { + d[i] = 0; + + // 0이 아니어서 단독으로 해석 가능한 경우 + if (s[i - 1] != '0') + { + d[i] += d[i - 1]; + } + + // 앞글자와 조합해서 유효한 두 자리가 될 수 있는 경우 + if (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')) + { + d[i] += d[i - 2]; + } + } + + return d[len]; + } +}; diff --git a/maximum-subarray/hwi-middle.cpp b/maximum-subarray/hwi-middle.cpp new file mode 100644 index 000000000..7349d2657 --- /dev/null +++ b/maximum-subarray/hwi-middle.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int maxSubArray(vector& nums) { + int cur = 0; + int ans = -1e5; + for (int n : nums) + { + // 이전까지 합이 음수라면 무조건 다시 시작하는게 이득 + if (cur < 0) + { + cur = 0; + } + + cur += n; + ans = max(cur, ans); + } + + return ans; + } +}; diff --git a/number-of-1-bits/hwi-middle.cpp b/number-of-1-bits/hwi-middle.cpp new file mode 100644 index 000000000..d3d81b139 --- /dev/null +++ b/number-of-1-bits/hwi-middle.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int hammingWeight(int n) { + // 아주 간편한 풀이가 있지만... + // return __builtin_popcount(n); + + // 직접 해보기 + int cnt = 0; + for (unsigned int i = 1 << 31; i > 0; i /= 2) + { + if ((n & i) != 0) + { + cnt++; + } + } + + return cnt; + } +}; diff --git a/valid-palindrome/hwi-middle.cpp b/valid-palindrome/hwi-middle.cpp new file mode 100644 index 000000000..3a39c7944 --- /dev/null +++ b/valid-palindrome/hwi-middle.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + bool isPalindrome(string s) { + int len = s.size(); + int l = 0; + int r = len - 1; + + while (l <= r) + { + while (l <= r &&!isalnum(s[l])) + { + l++; + } + + while (l <= r && !isalnum(s[r])) + { + r--; + } + + if (l > r) + { + break; + } + + if (tolower(s[l]) != tolower(s[r])) + { + return false; + } + + l++; + r--; + } + + return true; + } +};