leetcode ----Trie/stack专题

一:Implement Trie (Prefix
Tree)

题目:

Implement a trie with insertsearch,
and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

分析:此题是典型的trie树。能够參见:http://blog.csdn.net/lu597203933/article/details/44227431

代码:

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        for(int i = 0; i < 26; i++)
            next[i] = NULL;
        isString = false;
    }
    TrieNode *next[26];
    bool isString;
};

class Trie {
public:
    Trie() {
        root = new TrieNode();

    }

    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *p = root;
        for(int i = 0; i < s.size(); i++){
            if(p->next[s[i]-'a'] == NULL){
                p->next[s[i]-'a'] = new TrieNode();
            }
            p = p->next[s[i]-'a'];
        }
        p->isString = true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        TrieNode *p = root;
        for(int i = 0; i < key.size(); i++){
            if(p == NULL) return false;
            p = p->next[key[i]-'a'];
        }
        if(p == NULL || p->isString == false) return false;
        return true;

    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *p = root;
        for(int i = 0; i <= prefix.size(); i++){
            if(p == NULL) return false;
            p = p->next[prefix[i]-'a'];
        }
        return true;
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

二:Basic
Calculator

题目:

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ),
the plus + or minus sign -, non-negative integers
and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

分析:这道题能够将括号中面的看做是负负得正,这样用sign记录当前数字前面得符号。是+为1,是-为-1,。然后还要它所在的括号深度的符号,用stack来标记。

同一时候num = num *10 + c - ‘0‘。, 也给出了正向计算一个字符串比方“12342”的数值方法。。。

class Solution {
public:
    int calculate(string s) {
		int sign = 1;         // 当前元素前是+还是-
		stack<char> st;       // 主要是为了考虑括号的深度, 括号前面是+ 则为1否则为0
		st.push(1);
		int ans = 0;
		int tmp = 0;
		for(int i = 0; i < s.size(); i++){
			char c = s[i];
			if(isdigit(c)){    // 假设是数字  则保存起来
				tmp = tmp * 10 + s[i] - '0';
			}
			else if(c == '-' || c == '+'){
				ans += tmp * sign * st.top();   // 由当前符号和括号外面的符号两者决定!
				sign = (c=='+' ? 1 : -1);
				tmp = 0;
			}else if(c == '('){
				st.push(sign*st.top());   // 当前括号内元素的符号由其前面的各个外层括号符号决定
				sign = 1;   // 括号后面首个是+
			}else if(c ==')'){
				ans += tmp *sign * st.top();
				st.pop();
				tmp = 0;
				sign = 1;
			}
		}
		ans += tmp * sign * st.top();
        return ans;

    }
};
时间: 2024-10-14 04:34:41

leetcode ----Trie/stack专题的相关文章

LeetCode 单链表专题 (一)

目录 LeetCode 单链表专题 <c++> \([2]\) Add Two Numbers \([92]\) Reverse Linked List II \([86]\) Partition List \([82]\) Remove Duplicates from Sorted List II \([61]\) Rotate List \([19]\) Remove Nth Node From End of List LeetCode 单链表专题 <c++> \([2]\)

Leetcode之二分法专题-374. 猜数字大小(374. Guess Number Higher or Lower)

我们正在玩一个猜数字游戏. 游戏规则如下:我从 1 到 n 选择一个数字. 你需要猜我选择了哪个数字.每次你猜错了,我会告诉你这个数字是大了还是小了.你调用一个预先定义好的接口 guess(int num),它会返回 3 个可能的结果(-1,1 或 0): -1 : 我的数字比较小 1 : 我的数字比较大 0 : 恭喜!你猜对了! 示例 : 输入: n = 10, pick = 6 输出: 6 相似题目:Leetcode之二分法专题-278. 第一个错误的版本(First Bad Version

leetcode ----Trie专题

一:Implement Trie (Prefix Tree) 题目: Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. 分析:此题是典型的trie树,可以参见:http://blog.csdn.net/lu597203933/article/details/44227431

LeetCode Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e

[leetcode trie]212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same le

leetcode Implement Stack using Queues

Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty. Notes: You must use only s

Leetcode - 广度优先遍历专题

> 基础 1. 广度遍历优先是从给定的root节点开始,逐层次的向下访问各个节点: 2. 实现的方式是通过队列的先进先出,将从root节点开始的左孩子和右孩子压入到队列中,并顺序取出: 3. 由于是用队列实现,因此不存在用递归实现的方式. 下面是基本的广度遍历优先算法: 1 def breadthFirstSearch(root): 2 queue = [] 3 queue.append(root) 4 while queue: 5 node = queue[0] 6 queue.pop(0)

[LeetCode] Min Stack 栈

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum e

LeetCode: Min Stack 解题报告

Min Stack My Submissions Question Solution Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top