zoukankan      html  css  js  c++  java
  • 直通BAT面试算法精讲课1

    1.有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

    给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };*/
    
    class TreePrinter {
    public:
        vector<vector<int> > printTree(TreeNode* root) {
            // write code here
            queue<TreeNode*> q;
            int val = -1;
            TreeNode* last =nullptr;
            TreeNode* nlast =nullptr;
             TreeNode* cur =nullptr;
            nlast  = root;
            q.push(root);
            vector<int>v;
           vector<vector<int>>ret;
            while(!q.empty()){
                cur = q.front();
                q.pop();
     
                int val = cur->val;
                v.push_back(val);
                
       
                if(cur->left){
                    q.push(cur->left);
                    last = cur->left;
                }
                if(cur->right){
                    q.push(cur->right);
                    last = cur->right;
                }
                if(nlast == cur){
                    ret.push_back(v);
                    v.clear();
                    nlast = last;
                }
       
            }
            return ret;
            
            
        }
    };

    2.如果对于一个字符串A,将A的前面任意一部分挪到后边去形成的字符串称为A的旋转词。比如A="12345",A的旋转词有"12345","23451","34512","45123"和"51234"。对于两个字符串A和B,请判断A和B是否互为旋转词。

    给定两个字符串AB及他们的长度lenalenb,请返回一个bool值,代表他们是否互为旋转词。

    测试样例:
    "cdab",4,"abcd",4
    返回:true
    class Rotation {
    public:
        bool chkRotation(string A, int lena, string B, int lenb) {
            // write code here
            if(lena!=lenb){
                return false; 
            }
             
            string C= A+A;
            for(int i=0;i<lena;i++){
                string D=C.substr(i,lena);
               
                if(D==B)
                    return true;
            }
            return false;
                 
        }
    };
    View Code
    class Rotation {
    public:
        bool chkRotation(string A, int lena, string B, int lenb) {
            // write code here
            if(lena != lenb)
                return false;
            string AB = A+A;
            if(AB.find(B)!= string::npos ){
                return true;
                
            }else 
                return false;
        }
    };
  • 相关阅读:
    <C> 链表 双向链表 栈 队列
    <C> 结构体
    <C> getchar()函数 如何把getchar()到的字符串存起来的实际应用
    DataSet转换为泛型集合和DataRow 转成 模型类
    对DataSet,DataRow,DateTable转换成相应的模型
    Json对象与Json字符串互转(4种转换方式)
    Android开发 使用HBuilder的缓存方法
    MIT_AI公开课p1p2学习笔记
    LeetCode_02 两数相加【链表】
    leetcode_01两数之和
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/6127621.html
Copyright © 2011-2022 走看看