Leetcode Weekly Contest 131题解

1021. Remove Outermost Parentheses

题目:

A valid parentheses string is either empty (""), “(” + A + “)”, or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, “”, “()”, “(())()”, and “(()(()))” are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + … + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: “(()())(())”
Output: “()()()”
Explanation:
The input string is “(()())(())”, with primitive decomposition “(()())” + “(())”.
After removing outer parentheses of each part, this is “()()” + “()” = “()()()”.
Example 2:

Input: “(()())(())(()(()))”
Output: “()()()()(())”
Explanation:
The input string is “(()())(())(()(()))”, with primitive decomposition “(()())” + “(())” + “(()(()))”.
After removing outer parentheses of each part, this is “()()” + “()” + “()(())” = “()()()()(())”.
Example 3:

Input: “()()”
Output: “”
Explanation:
The input string is “()()”, with primitive decomposition “()” + “()”.
After removing outer parentheses of each part, this is “” + “” = “”.

Note:

S.length <= 10000
S[i] is “(” or “)”
S is a valid parentheses string

题目意思:就是把外层括号去掉。

解析:我们可以找匹配,如果找到了匹配的括号,那么我们就进行判断,如果是相邻的,直接忽略掉,如果是不相邻的,
那么我们就判断这个区间是否为偶数,且左括号和有括号是否匹配,因为可能出现如下的情况。
((()   这种也会偶数,左右括号也匹配,但是左右括号数不相等
所以 if(S[i]==')' && (i-l+1)%2==0 && left == right) 来判断

代码:

class Solution
{
public:
    string removeOuterParentheses(string S)
    {
        string ans = "";
        int s_len = S.length();
        if(s_len == 0) return 0;
        int l = 0;
        int left = 1;
        int right = 0;
        for(int i = 1; i < s_len; i++)
        {
            if(S[i]=='(') left++;
            else right++;
            if(S[i]==')' && (i-l+1)%2==0 && left == right)
            {
                for(int j = l+1; j < i; j++)
                    ans += S[j];
                l = i+1;
               // cout << l << endl;
            }
            else if(S[i]==')' && i-l+1==2) l = l + 1;
        }
        return ans;
    }
};

1022. Sum of Root To Leaf Binary Numbers

Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers.

Example 1:

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

The number of nodes in the tree is between 1 and 1000.
node.val is 0 or 1.
The answer will not exceed 2^31 - 1.

这个题就不说了,就是dfs,但是切记每次加了以后就要mod

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
public:
    const int MOD = 1e9+7;
    void dfs(TreeNode* root, long long cur_sum,int &ans)
    {
       if(root->left == nullptr && root->right == nullptr)
       {
           ans += cur_sum;
           ans %= MOD;
           return;
       }
       if(root->left) dfs(root->left,(cur_sum*2+root->left->val)%MOD,ans);
       if(root->right) dfs(root->right,(cur_sum*2+root->right->val)%MOD,ans);
    }
    int sumRootToLeaf(TreeNode* root)
    {
        if(root == nullptr) return 0;
        int ans = 0;
        long long cur_sum = root->val;
        dfs(root,cur_sum,ans);
        return ans;
    }
};

Leetcode 1023. Camelcase Matching

A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.)

Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and only if queries[i] matches the pattern.

Example 1:

Input: queries = [“FooBar”,“FooBarTest”,“FootBall”,“FrameBuffer”,“ForceFeedBack”], pattern = “FB”
Output: [true,false,true,true,false]
Explanation:
“FooBar” can be generated like this “F” + “oo” + “B” + “ar”.
“FootBall” can be generated like this “F” + “oot” + “B” + “all”.
“FrameBuffer” can be generated like this “F” + “rame” + “B” + “uffer”.
Example 2:

Input: queries = [“FooBar”,“FooBarTest”,“FootBall”,“FrameBuffer”,“ForceFeedBack”], pattern = “FoBa”
Output: [true,false,true,false,false]
Explanation:
“FooBar” can be generated like this “Fo” + “o” + “Ba” + “r”.
“FootBall” can be generated like this “Fo” + “ot” + “Ba” + “ll”.
Example 3:

Input: queries = [“FooBar”,“FooBarTest”,“FootBall”,“FrameBuffer”,“ForceFeedBack”], pattern = “FoBaT”
Output: [false,true,false,false,false]
Explanation:
“FooBarTest” can be generated like this “Fo” + “o” + “Ba” + “r” + “T” + “est”.

Note:

1 <= queries.length <= 100
1 <= queries[i].length <= 100
1 <= pattern.length <= 100
All strings consists only of lower and upper case English letters.

题意:就是根据模式串,看是否能找到匹配,且匹配串之间不含有大写字母。

解析:首先得满足一个条件,那就是匹配串和模式串的大写字母必须相同,不然不可能是合法的匹配。 然后就是匹配阶段了,
其实用栈把模式串存起来,然后从后往前,遇到和栈顶匹配的,那么就退栈,看最后栈是否为空即可。

代码:

class Solution
{
public:
    vector<bool> camelMatch(vector<string>& queries, string pattern)
    {
        int p_len = pattern.length();
        int upper_cnt = 0;
        stack<char> st;
        for(int i = 0 ; i < p_len; i++)
        {
            if(pattern[i]>='A' && pattern[i]<='Z') upper_cnt++;
            st.push(pattern[i]);
        }
      //  cout << upper_cnt << endl;
        int s_len = queries.size();
        vector<bool> ans;
        stack<char>temp;
        for(int i = 0; i < s_len; i++)
        {
            string s = queries[i];
            while(!temp.empty()) temp.pop();
            temp = st;
            int s_len = s.length();
            int upper = 0;
            for(int j = 0 ; j < s_len; j++)
                if(s[j]>='A' && s[j]<='Z') upper++;
          //  cout << upper << endl;
            if(upper!=upper_cnt) ans.push_back(false);
            else
            {
                for(int j = s_len-1; j>=0; j--)
                    if(s[j]==temp.top()) temp.pop();
                if(temp.empty())
                {
                   // cout << "1" << endl;
                    ans.push_back(true);
                }
                else
                {
                    //cout << "0" << endl;
                    ans.push_back(false);
                }
            }
        }
        return ans;
    }
};

1024. Video Stitching

You are given a series of video clips from a sporting event that lasted T seconds. These video clips can be overlapping with each other and have varied lengths.

Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time clips[i][1]. We can cut these clips into segments freely: for example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].

Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]). If the task is impossible, return -1.

Example 1:

Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10
Output: 3
Explanation:
We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut [1,9] into segments [1,2] + [2,8] + [8,9].
Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].
Example 2:

Input: clips = [[0,1],[1,2]], T = 5
Output: -1
Explanation:
We can’t cover [0,5] with only [0,1] and [0,2].
Example 3:

Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], T = 9
Output: 3
Explanation:
We can take clips [0,4], [4,7], and [6,9].
Example 4:

Input: clips = [[0,4],[2,8]], T = 5
Output: 2
Explanation:
Notice you can have extra video after the event ends.

Note:

1:1 <= clips.length <= 100
2:0 <= clips[i][0], clips[i][1] <= 100
3:0 <= T <= 100

这题两种解法。

1:每次找到一个尽可能大的区间,然后合并,例如最开始设置区间为[0,0],那么下次我们找到的区间[L,R]满足,L在0左边且可以重合,
R满足尽可能的大,每次这样更新,指到到了T,如果有一次cur = last,说明没有更大的区间了,那么到不了T,则返回-1

代码:

class Solution 
{
public:
    int videoStitching(vector<vector<int>>& clips, int T) 
    {
    	int cur,last;
    	cur = last = 0;
    	int ans = 0;
    	int n = clips.size();
    	while(true)
    	{
    		for(int i = 0 ; i < n; i++)
    			if(clips[i][0]<=cur && clips[i][1] > last) last = clips[i][1];
    		if(cur!=last)
    		{
    			cur = last;
    			ans++;
    			if(cur>=T) break;
    		}
    		else return -1;
    	}
    	return ans;
    }
};

2:动态规划

我们设置dp[0]为0,然后首先对区间进行排序,然后逐个对区间进行更新,动态转移方程为 dp[r] = min(dp[r],dp[j]+1);
最后看能否更新到dp[T]

代码:

class Solution 
{
public:

    static bool cmp(vector<int> a, vector<int> b)
    {
      if(a[0]==b[0]) return a[1] < b[1];
      return a[0] < b[0];
    } 
    int videoStitching(vector<vector<int>>& clips, int T) 
    {
      int n;
      n = clips.size();
      sort(clips.begin(), clips.end(), cmp);
        vector<int> dp(T+1,200);
        if(clips[0][0]!=0) return -1;
        dp[0] = 0;
        for(int i = 0; i < n; i++)
        {
          int l = clips[i][0];
          int r = min(T,clips[i][1]);
          for(int j = l; j <= r; j++)
            dp[r] = min(dp[r],dp[j]+1);
        }
        return dp[T]==200?-1:dp[T];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值