diff --git a/C++/ValidParentheses.cpp b/C++/ValidParentheses.cpp new file mode 100644 index 00000000..5d37f82a --- /dev/null +++ b/C++/ValidParentheses.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +class Solution { +public: + bool isValid(std::string s) { + + // Odd-length strings cannot be valid + if(s.length() % 2 != 0) { + return false; + } + + // Map parentheses pairs + std::unordered_map parentheses = { {')', '('}, {']', '['}, {'}', '{'} }; + std::stack characters; + + for (char current_char : s) { + // Check if the current character is a closing parentheses + if (parentheses.find(current_char) != parentheses.end()) { + // If the stack is empty or the stack top doesn't match the current closing parentheses type, return false + if (characters.empty() || characters.top() != parentheses[current_char]) { + return false; + } + // Otherwise, the parentheses match and the top element can be popped + characters.pop(); + } + else { + // If current_char is not in the map, then that means it is an open parentheses, and can be pushed onto the stack + characters.push(current_char); + } + } + return characters.empty(); + } +}; \ No newline at end of file diff --git a/Java/128.Longest-Consecutive-Sequence.java b/Java/128.Longest-Consecutive-Sequence.java new file mode 100644 index 00000000..75f56e19 --- /dev/null +++ b/Java/128.Longest-Consecutive-Sequence.java @@ -0,0 +1,34 @@ +import java.util.HashSet; +import java.util.Set; + +class Solution { + public int longestConsecutive(int[] nums) { + if (nums.length == 0) { + return 0; + } + + Set numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); + } + + int longestStreak = 0; + + for (int num : numSet) { + // check if it's the start of a sequence + if (!numSet.contains(num - 1)) { + int currentNum = num; + int currentStreak = 1; + + while (numSet.contains(currentNum + 1)) { + currentNum += 1; + currentStreak += 1; + } + + longestStreak = Math.max(longestStreak, currentStreak); + } + } + + return longestStreak; + } +} \ No newline at end of file