(栈)leetcode 394

Myth丶恋晨 2021-12-10 02:27 253阅读 0赞

1266918-20190711231559977-341210834.png

思路:分情况讨论+栈。

  1. class Solution {
  2. public:
  3. string decodeString(string s) {
  4. stack<int> nums;
  5. stack<string> ch;
  6. int num = 0;
  7. string str = "";
  8. for(auto c:s){
  9. if(isdigit(c))
  10. num = num*10 + (c-'0');
  11. else if(isalpha(c))
  12. str += c;
  13. else if(c=='['){
  14. ch.push(str);
  15. nums.push(num);
  16. str = "";
  17. num = 0;
  18. }
  19. else{
  20. string tmp = str;
  21. for(int i=0; i<nums.top()-1; ++i)
  22. //本身一次已经在内,故nums.top()-1
  23. str += tmp;
  24. //这里字符相加的顺序不能颠倒
  25. str = ch.top()+str;
  26. nums.pop();
  27. ch.pop();
  28. }
  29. }
  30. return str;
  31. }
  32. };

1266918-20190715112933407-916952630.png

思路:递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
  13. int size = nums.size();
  14. if(size == 0)
  15. return NULL;
  16. return MaxTree(nums, 0, size-1);
  17. }
  18. TreeNode* MaxTree(vector<int>& nums, int left, int right){
  19. if(left > right)
  20. return NULL;
  21. int max_index = maxIndex(nums, left, right);
  22. TreeNode* head = new TreeNode(nums[max_index]);
  23. head->left = MaxTree(nums, left, max_index-1);
  24. head->right = MaxTree(nums, max_index+1, right);
  25. return head;
  26. }
  27. int maxIndex(vector<int>& nums, int left, int right){
  28. int index = left, m = nums[left];
  29. for(int i=left; i<=right; ++i){
  30. if(nums[i]>m){
  31. m = nums[i];
  32. index = i;
  33. }
  34. }
  35. return index;
  36. }
  37. };

转载于:https://www.cnblogs.com/Bella2017/p/11173459.html

发表评论

表情:
评论列表 (有 0 条评论,253人围观)

还没有评论,来说两句吧...

相关阅读