본문 바로가기

LeetCode

(5)
[Leetcode/C++] 1047. Remove All Adjacent Duplicates In String class Solution { public: string removeDuplicates(string s) { string answer; for(auto &ch : s) { if(answer.back() == ch) answer.pop_back(); else answer.push_back(ch); } return answer; } }; 중복되는 문자열을 제거하라는 것이 이번 문제의 요약이다! 그런데 문자열을 새로운 문자열에 넣는다고 생각하면 stack자료구조를 이용할 수 있다! Stack에 새로 넣는 것과 가장 top에 쌓여있는 것이 같다면 stack에서 꺼내는 것으로 생각하면 문제가 단순해진다. 이 코드로 빠르면 runtime이 13ms까지는 나온다 만약 auto에서 &를 이용해 복사 연산자를 사용하면..
[Leetcode/C++] 551. Student Attendance Record I class Solution { public: bool checkRecord(string s) { return s.find("LLL") != string::npos || count(s.begin(), s.end(), 'A') > 1 ? false : true; } }; string에 내장되어있는 find 함수를 이용해 LLL을 찾았거나 결석(A) 가 2번이상이면 false를 리턴하도록 구현하였다. stiring의 find 함수는 algorithm의 find 함수와 다르게 find(찾을문자, 시작점)을 주어준다. 문제: https://leetcode.com/problems/student-attendance-record-i/ Student Attendance Record I - LeetCode Level up..
[LeetCode/C++] 14. Longest Common Prefix class Solution { public: string longestCommonPrefix(vector& strs) { if(strs.empty()) return ""; sort(strs.begin(), strs.end()); string smallest = strs[0]; string biggest = strs[strs.size()-1]; string answer = ""; for(int i = 0; i < biggest.size(); i++) { if(smallest[i] == biggest[i]) answer += smallest[i]; else break; } return answer; } }; 맨 처음에는 모든 벡터를 돌아가면서 첫 문자부터 가장 길이가 짧은 문자열까지 반복하며 비교하는 것을 ..
[LeetCode/C++] 844. Backspace String Compare class Solution { public: bool backspaceCompare(string s, string t) { string a = ""; string b = ""; for(int i = 0; i < s.length(); i++) { if(!a.empty() && s[i] == '#') a.pop_back(); if(s[i] != '#') a.push_back(s[i]); } for(int j = 0; j < t.length(); j++) { if(!b.empty() && t[j] == '#') b.pop_back(); if(t[j] != '#') b.push_back(t[j]); } return a.compare(b) == 0 ? true : false; } }; 이 문제는 #이 뒤로가기 버..
[Leetcode/C++] 66. Plus One class Solution { public: vector plusOne(vector& digits) { int carry = 1; for(int i = digits.size()-1; i >= 0; i--) { if(digits[i] == 9 && carry == 1) { digits[i] = 0; carry = 1; } else { digits[i] += carry; carry = 0; } } if(digits[0] == 0) digits.insert(digits.begin(), 1); return digits; } }; 논리설계 수업 때 2진수 ADDER를 만들던게 생각나는 문제였습니다. carry(올림 숫자)를 추가해 9일 때 올림 숫자를 받게 되면 올림 숫자는 그대로 가져가고 자리수는 0으로 바꿔주..