Skip to content

[crumbs22] Week 03 solutions #1314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions maximum-subarray/crumbs22.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <iostream>
#include <vector>
#include <climits>

using namespace std;


/*
TC: O(n)
SC: O(1)
풀이 방법:
- sum에 현재 값을 더해가면서 최대값을 갱신한다
- 누적합이 음수가 됐을 때 0으로 리셋한다

고민했던 케이스(left와 right 포인터를 두고 풀었을 때):
[-2, -1]
[-1, -2]
[-2, 1]
[-1, 1, 2, 1]
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {

int max = nums[0];
int sum = 0;

for (int i = 0; i < nums.size(); i++)
{
sum += nums[i];
if (sum > max)
max = sum;
if (sum < 0)
sum = 0;
}
return (max);
}
};
26 changes: 26 additions & 0 deletions number-of-1-bits/crumbs22.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <iostream>

using namespace std;

/*
TC: O(1)
SC: O(1)
풀이방법:
- n의 비트를 오른쪽으로 이동시키면서 최하위 비트가 1인지 확인한다
- n이 int형이므로 cnt는 32를 넘을 수 없다
*/

class Solution {
public:
int hammingWeight(int n) {
int cnt = 0;

while (n && cnt <= 31)
{
if (n & 1)
cnt++;
n >>= 1;
}
return (cnt);
}
};
39 changes: 39 additions & 0 deletions valid-palindrome/crumbs22.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

/*
TC: O(n)
start, end 포인터가 각각 한 번씩 전체 문자열을 스캔하기 때문에
모든 문자를 최대 한 번씩만 검사한다
SC: O(1)
풀이방법:
- 양 쪽에서 포인터가 이동하면서 두 포인터가 만날 때까지 반복하며 두 문자가 일치하는지 확인한다
고민했던 케이스:
- 0P
*/

class Solution {
public:
bool isPalindrome(string s) {
int start = 0;
int end = s.size() - 1;

while (start < end)
{
// ascii 문자가 아닌 구간 건너뛰기
while (start < end && !isalnum(s[start]))
start++;
while (start < end && !isalnum(s[end]))
end--;

if (tolower(s[start]) != tolower(s[end]))
return (false);
start++;
end--;
}
return (true);
}
};