leetcode

目录

leetcode刷题小结

730 统计不同回文子字符串(DP)

如果 S[i] == S[j],这时我们需要判断[i, j]这一段中有多少字符与S[i]不相等
如果中间没有和S[i]相同的字母,
例如"aba"这种情况,dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
如果中间只有一个和S[i]相同的字母,
就是"aaa"这种情况,dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
否则中间至少有两个和S[i]相同的字母,
就是"aabaa"这种情况,dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1];
否则dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
时间复杂度:\(O(n^2*log(n))\),但是在leetcode上跑的比\(O(n^3)\)还慢,数据太水了。

class Solution {
public:
    int countPalindromicSubsequences(string S) {
        int len = S.length(), i = 0, mod = 1000000007;
        vector<vector<int>> dp(len, vector<int>(len, 0));
        vector<vector<int>> pos(4);
        for(char c: S) {
            pos[c-'a'].emplace_back(i);
            dp[i][i] = 1;
            ++ i;
        }
        for(int d = 2; d <= len; ++d) {
            for(i = 0; i + d - 1 < len; ++i) {
                int j = i + d - 1;
                if(S[i] == S[j]) {
                    int left = upper_bound(begin(pos[S[i]-'a']), end(pos[S[i]-'a']), i) - begin(pos[S[i]-'a']);
                    int right = prev(lower_bound(begin(pos[S[j]-'a']), end(pos[S[j]-'a']), j)) - begin(pos[S[j]-'a']);
                    // if(left > right) {
                    //     dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
                    // }else if(left == right) {
                    //     dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
                    // }else {
                    //     left = pos[S[i]-'a'][left];
                    //     right = pos[S[j]-'a'][right];
                    //     dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1];
                    // }
                    dp[i][j] = left > right?dp[i + 1][j - 1] * 2 + 2:(left<right?dp[i + 1][j - 1] * 2 - dp[pos[S[i]-'a'][left] + 1][pos[S[j]-'a'][right] - 1]:dp[i + 1][j - 1] * 2 + 1);
                }else {
                    dp[i][j] = d > 2? (dp[i][j - 1] + dp[i + 1][j]) - dp[i + 1][j - 1]: 2;
                }
                dp[i][j] >= mod?dp[i][j]%=mod:(dp[i][j]<0?dp[i][j]+=mod:0);
            }
        }
        return dp[0][len - 1];
    }
};

小的线程例子

#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
void *myThread1(void) {
    int i;
    for(i = 0; i < 100; ++i) {
	printf("This is the 1st pthread created.\n");
	sleep(1);
    }
}
void *myThread2(void) {
    int i;
    for(i = 0; i < 100; ++i) {
	printf("This is the 2nd pthread created.\n");
	sleep(1);
    }
}
int main() {
    int i = 0, ret = 0;
    pthread_t id1, id2;
    ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
    if(ret) {
	printf("Create pthread error!\n");
	return 1;
    }
    ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
    if(ret) {
	printf("Create pthread error!\n");
	return 1;
    }
    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
    return 0;
}
posted @ 2019-11-22 12:06  Cwolf9  阅读(188)  评论(0编辑  收藏  举报