LeetCode周练Contest-35代码解析(C++)

写在前面:

LeetCode这个网站相比不必多说了吧,凡是IT圈子的人应该都知道这个网站,最近开始准备找工作,当然也免不了上去刷刷题,做一做比较经典的编程题,刚好看到LeetCode有个周练,便报名参加。

最近一直在忙着做深度学习的项目,主要是关于人脸识别(身份识别),所以虽然周末抽空参加了LeetCode的周练,但是都没有时间总结,今天抽点空将之前的练习记录写上来;

进入正题:

概要: 总共4个题,一个半小时的时间安排。题目分级为,两个easy,一个medium,一个hard。

第一题 605. Can Place Flowers

题目描述

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.


难度为easy的第一道题,利用规则来遍历一遍即可,在每一个取值为0的位置,看看左右两边是否都是0,如果是的话,统计该点为可种植鲜花的点,同时将该部分的值置为1。

//一维数组的题目
//用规则遍历一遍即可
class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int lens = flowerbed.size();
        int sum = 0;
        for(int i=0;i<lens;i++){
            if(flowerbed[i] == 0){
                int left_right = (i-1<0?0:flowerbed[i-1]) + (i+1>=lens?0:flowerbed[i+1]);
                if(left_right == 0){
                    flowerbed[i] = 1;
                    ++sum;
                }
            }
        }
        if(sum >= n)    return true;
        else    return false;
    }
};

第二题 606. Construct String from Binary Tree

题目描述

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.


首先要明确一点,在遇到树形结构的题目时,大部分情况下只需要考虑两种做法,一种是dfs,一种就是递归;如果区分不要那么完全的话,可以理解为考虑递归就够了,毕竟dfs大部分时候借助递归的形式是最方便的。

回到题目上,其实就是序列化一个树形结构的数据,规则为除了根节点,之后每一个子树都要用括号来包含住,然后在其中,还需要单独的两个括号来包住左右子树,根节点不用包含,要注意的一点是,如果右子树为空,可以省略,但是左子树无论什么情况下都不能省略,如果为空的话,也要有一对空括号来表达。

/**
 * 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 {
private:
    string output;
    string preorderRecursive(TreeNode* t){
        if(t == NULL)   return "()";
        string ret = "(";
        ret += to_string(t->val);
        //使用逻辑判断哪个时候该接受子树返回的值
        string left = preorderRecursive(t->left);
        string right = preorderRecursive(t->right);
        int left_val = left.compare("()"), right_val = right.compare("()");
        if(right_val != 0) ret += left + right;
        else if(left_val != 0 && right_val == 0)   ret += left;
        ret += ")";
        return ret;
    }
public:
    string tree2str(TreeNode* t) {
        output.clear();
        if(t == NULL)   return output;
        //为了防止节点有负数,所以需要直接转为字符串
        output += to_string(t->val);
        string left = preorderRecursive(t->left);
        string right = preorderRecursive(t->right);
        int left_val = left.compare("()"), right_val = right.compare("()");
        if(right_val != 0) output += left + right;
        else if(left_val != 0 && right_val == 0)   output += left;
        return output;
    }
};

第三题 609. Find Duplicate File in System

题目描述

Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.

A group of duplicate files consists of at least two files that have exactly the same content.

A single directory info string in the input list has the following format:

"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

It means there are n files (f1.txt, f2.txt ... fn.txt with content f1_content, f2_content ... fn_content, respectively) in directory root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

"directory_path/file_name.txt"


这个题虽然是一个medium难度的题目,而且题目描述也挺长的,但是其实特别简单,主要考察的对象我认为是字符串;

解题思路,可以通过分解字符串,分解为目录和文件,然后用一个hash-table来维护同一个文件内容的文件路径即可。

//祝贺一次通过
//本题不难,主要考察字符串的用法,主要是find方法和string::npos注意一下即可
class Solution {
public:
    vector<vector<string>> findDuplicate(vector<string>& paths) {
        //首先考虑空值的边界情况
        int lens = paths.size();
        if(lens == 0)   return vector<vector<string>>();
        //开始做,用一个hash表来维护
        unordered_map<string, vector<string>> tables;
        for(int i=0;i<lens;i++){
            int dir_pos = paths[i].find(' ');
            string dir_name = paths[i].substr(0, dir_pos);
            int file_pos = dir_pos, pre_pos = file_pos+1;
            //先分割路径字符串和文件字符串,然后循环获取文件
            while((file_pos = paths[i].find(' ', pre_pos)) != string::npos) {
                string file_with_content = paths[i].substr(pre_pos, file_pos - pre_pos);
                int pos = file_with_content.find('(');
                //获取文件和内容的列表以后
                //用左括号做分割,以content为key,将路径+文件名字符串放入hash表
                int tmp_lens = file_with_content.size();
                string file = file_with_content.substr(0, pos);
                string content = file_with_content.substr(pos+1, tmp_lens - 2 - pos);
                tables[content].push_back(dir_name+"/"+file);
                pre_pos = file_pos + 1;
            }
            //别忘了还有最后一个文件需要获取
            string file_with_content = paths[i].substr(pre_pos);
            int pos = file_with_content.find('(');
            int tmp_lens = file_with_content.size();
            string file = file_with_content.substr(0, pos);
            string content = file_with_content.substr(pos+1, tmp_lens - 2 - pos);
            tables[content].push_back(dir_name+"/"+file);
        }
        //只选择内容重复数量为2的key
        vector<vector<string>> ret;
        for(auto k=tables.begin();k!=tables.end();k++){
            if(k->second.size() > 1)    ret.push_back(k->second);
        }
        return ret;
    }
};

总结:

找工作路漫漫,但求不忘初心,回首对得起走过的路。

代码地址:[luuuyi/leetcode-contest]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值