zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:Reverse Words in a String   

    Given an input string, reverse the string word by word.

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

    Clarification:
    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words?
      Reduce them to a single space in the reversed string.

     

    class Solution {
    public:
        void swap(char& a, char& b){
            int tmp = a;
            a = b;
            b = tmp;
        }
        void reverse(string &s, int begin, int end){
            if (s[begin] == '' || s[end] == ''){
                return;
            }
            while (begin < end){
                swap(s[begin], s[end]);
                begin++;
                end--;
            }
        }
        void reverseWords(string &s) {
            if (s[0] == '' || s.empty()){
                return;
            }
            reverse(s, 0, s.length() - 1);
            //*/
            int start = 0, end = 0, len = 0;
            while (start < s.length()){
                while (start != s.length() && s[start] == ' ') start++;
                for (end = start; end != s.length() && s[end] != ' '; end++);
                if (len != 0 && end > start) s[len++] = ' ';
                if (end > start){
                    reverse(s, start, end - 1);
                }
                while (start < end) s[len++] = s[start++];
                
            }
            s.resize(len);
            //*/
        }
    };

    Evaluate Reverse Polish Notation

     

    Evaluate the value of an arithmetic expression in Reverse Polish Notation.

    Valid operators are +-*/. Each operand may be an integer or another expression.

    Some examples:

      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
      ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            stack<int> st;
            int operand_a = 0, operand_b = 0, tmp;
            stringstream ss;
            vector<string>::iterator it;
            for(it = tokens.begin(); it != tokens.end(); it++){
                ss.clear();
                if ((*it) == "+" ){
                    operand_b = st.top(); st.pop();
                    operand_a = st.top(); st.pop();
                    st.push(operand_a + operand_b);
                }
                else if ((*it) == "-" ){
                    operand_b = st.top(); st.pop();
                    operand_a = st.top(); st.pop();
                    st.push(operand_a - operand_b);
                }
                else if ((*it) == "*" ){
                    operand_b = st.top(); st.pop();
                    operand_a = st.top(); st.pop();
                    st.push(operand_a * operand_b);
                }
                else if ((*it) == "/" ){
                    operand_b = st.top(); st.pop();
                    operand_a = st.top(); st.pop();
                    st.push(operand_a / operand_b);
                }
                else{
                    ss.str(*it);
                    ss >> tmp;
                    st.push(tmp);
                }
            }
            return st.top();
        }
    };

     Max Points on a Line

         思路:用斜率来计算(同一个点的情况特殊处理)。可以用字符串来代替double类型的斜率比较。

    /**
    * Definition for a point.
    * struct Point {
    *     int x;
    *     int y;
    *     Point() : x(0), y(0) {}
    *     Point(int a, int b) : x(a), y(b) {}
    * };
    */
    class Solution {
    public:
        int maxPoints(vector<Point> &points) {
            int ans = 0;
    
            vector<Point>::iterator first, second;
            for (first = points.begin(); first != points.end(); first++){
                map<string, int> record_map;
                int same_point = 0, tmp_ans = 0;
                for (second = first + 1; second != points.end(); second++){
                    int x = (*second).x - (*first).x, y = (*second).y - (*first).y;
                    if (x==0 && y==0){
                        same_point ++;
                        continue;
                    }
                    /*计算斜率*/
                    int g = gcd(x, y);
                    if (g){ /*非同一个点*/
                        x = x / g;
                        y = y / g;
                    }
                    string str_tmp = to_string(x) + " " + to_string(y);
                    if (record_map.find(str_tmp) != record_map.end()){
                        record_map[str_tmp] += 1;
                    }
                    else{
                        record_map[str_tmp] = 1;
                    }
                    tmp_ans = max(tmp_ans, record_map[str_tmp]);
                }
                ans = max(tmp_ans + 1 + same_point, ans);
            }
    
            return ans;
        }
    private:
        int gcd(int x, int y){
            if (y){
                return gcd(y, x % y);
            }
            else{
                return x;
            }
        }
    };

    Best Time to Buy and Sell Stock

      Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

      用类似动态规划的思想,到第i天买入,那么我能赚到的最大利润是: i + 1 ~ n天中最大的股价减去第i天的。找最大股价的问题可以在找第i+1~n天的最大利润时顺便记录。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if (prices.size() <= 1) return 0;
            
            int ans = 0;
            int max_price = prices[prices.size() - 1];
            
            for (int i = prices.size() - 1; i >= 0; i--) {
                max_price = max(max_price, prices[i]);
                ans = max(ans, max_price - prices[i]);
            }
            return ans;
        }
    };

    Set Matrix Zeroes

    Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

    class Solution {
    public:
        void setZeroes(vector<vector<int> > &matrix) {
            if (matrix.empty()) return;
            int rows = matrix.size(), cols = matrix[0].size();
    
            //利用原矩阵的一行和一列 来保存行和列是否有0,再次遍历数组时查询对应的行和列然后修改值;
            //空间复杂度为O(1)
            int x = -1, y = -1;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (matrix[i][j] == 0) {
                        if (x == -1) {
                            x = i, y = j;
                        }
                        else {
                            matrix[x][j] = 0;
                            matrix[i][y] = 0;
                        }
                    }
                }
            }
            if (x == -1) return; // 没有0 存在
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if ((matrix[x][j] == 0 || matrix[i][y] == 0) && (i != x && j != y)) {
                        matrix[i][j] = 0;
                    }
                }
            }
            for (int j = 0; j < cols; j++) matrix[x][j] = 0;
            for (int i = 0; i < rows; i++) matrix[i][y] = 0;
        }
    };

    Combinations

    Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

    For example,
    If n = 4 and k = 2, a solution is:

    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]

    思路:
    开一个数组,其下标表示1到m个数,数组元素的值为1表示其下标
    代表的数被选中,为0则没选中。 
    首先初始化,将数组前n个元素置1,表示第一个组合为前n个数。 
    然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为 
    “01”组合,同时将其左边的所有“1”全部移动到数组的最左端。 
    当第一个“1”移动到数组的m-n的位置,即n个“1”全部移动到最右端时,就得 
    到了最后一个组合。 
    例如求5中选3的组合: 
    1 1 1 0 0 //1,2,3 
    1 1 0 1 0 //1,2,4 
    1 0 1 1 0 //1,3,4 
    0 1 1 1 0 //2,3,4 
    1 1 0 0 1 //1,2,5 
    1 0 1 0 1 //1,3,5 
    0 1 1 0 1 //2,3,5 
    1 0 0 1 1 //1,4,5 
    0 1 0 1 1 //2,4,5 
    0 0 1 1 1 //3,4,5 
    class Solution {
    public:
        bool judge(vector<bool> counter) {
            bool is_one = false;
            for (int i = 0; i < counter.size(); i++) {
                if (counter[i] == true) {
                    is_one = true;
                }
                if (is_one && counter[i] == false) {
                    return false;
                }
            }
            return true;
        }
        vector<vector<int> > combine(int n, int k) {
            vector<vector<int>> ans;
            if (k > n) return ans;
    
            vector<int> cur_ans;
            vector<bool> counter(n, false);
            for (int i = 0; i < k; i++) {
                counter[i] = true;
                cur_ans.push_back(i + 1);
            }
            ans.push_back(cur_ans);
            
            
            do {
                int pos = 0;
                while (pos < n - 1 && !(counter[pos] && !counter[pos + 1])) pos++; //找到第一个10
                if (pos == n - 1) break;
                counter[pos] = false, counter[pos + 1] = true; // change it to 01
    
                //统计1的个数
                int one_num = 0;
                for (int i = 0; i < pos; i++) {
                    if (counter[i]) one_num++;
                }
                //将1移动到左边
                for (int i = 0; i < one_num; i++) {
                    counter[i] = true;
                }
                for (int i = one_num; i < pos; i++) {
                    counter[i] = false;
                }
    
                //保存结果
                cur_ans.clear();
                for (int i = 0; i < n; i++) {
                    if (counter[i]) {
                        cur_ans.push_back(i + 1);
                    }
                }
                ans.push_back(cur_ans);
    
            } while (!judge(counter));
    
            return ans;
        }
    };

    Word Search

     Total Accepted: 7591 Total Submissions: 39320My Submissions

    Given a 2D board and a word, find if the word exists in the grid.

    The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

    For example,
    Given board =

    [
      ["ABCE"],
      ["SFCS"],
      ["ADEE"]
    ]
    
    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.
     
    解题思路:循环遍历每个字符,如该字符与word中的第一个字符相等,则DFS搜索。
     1 class Solution {
     2 public:
     3     bool dfs(vector<vector<char>> &board, int i, int j, vector<vector<bool>> &visited, string &word, int idx) {
     4         if (idx == word.length() - 1) {
     5             return true;
     6         }
     7         else {
     8             bool find = false;
     9             if (i > 0 && !visited[i-1][j] && board[i - 1][j] == word[idx + 1]){//向上搜索
    10                 visited[i - 1][j] = true;
    11                 find = dfs(board, i - 1, j, visited, word, idx + 1);
    12                 visited[i - 1][j] = false;
    13             }
    14 
    15             if (!find && i < board.size() - 1 && !visited[i + 1][j] && board[i + 1][j] == word[idx + 1]) {//向下搜索
    16                 visited[i + 1][j] = true;
    17                 find = dfs(board, i + 1, j, visited, word, idx + 1);
    18                 visited[i + 1][j] = false;
    19             }
    20 
    21             if (!find && j > 0 && !visited[i][j - 1] && board[i][j - 1] == word[idx + 1]) {//向左搜索
    22                 visited[i][j - 1] = true;
    23                 find = dfs(board, i, j - 1, visited, word, idx + 1);
    24                 visited[i][j - 1] = false;
    25             }
    26 
    27             if (!find && j < board[0].size() - 1 && !visited[i][j + 1] && board[i][j + 1] == word[idx + 1]) {//向右搜索
    28                 visited[i][j + 1] = true;
    29                 find = dfs(board, i, j + 1, visited, word, idx + 1);
    30                 visited[i][j + 1] = false;
    31             }
    32             return find;
    33         }
    34     }
    35     bool exist(vector<vector<char> > &board, string word) {
    36         if (board.empty() || word.empty()) return false;
    37 
    38         int rows = board.size(), cols = board[0].size();
    39         vector<vector<bool>> visited(rows, vector<bool>(cols, false));
    40         for (int i = 0; i < rows; i++) {
    41             for (int j = 0; j < cols; j++) {
    42                 if (board[i][j] == word[0]){
    43                     visited[i][j] = true; 
    44                     if (dfs(board, i, j, visited, word, 0)) return true;
    45                     visited[i][j] = false;
    46                 }
    47             }
    48         }
    49         return false;
    50     }
    51 };
  • 相关阅读:
    微信支付接口开发时遇到的问题
    记录一次特别瞎的问题。。。
    二叉树的三种遍历(java实现)
    【转】redis实现的分布式锁
    @RequestParam、@ReqeustBody、@ReponseBody认识
    同步、异步、阻塞、非阻塞
    multipart/form-data和application/x-www-form-urlencoded区别
    HTTP请求的502、504、499错误
    Nginx配置CI框架问题(Linux平台下Centos系统)
    mac中更改xampp的根目录
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3635407.html
Copyright © 2011-2022 走看看