Python is validate by indent before each line of code, so given a list of Strings
which indicates the lines of Python code. Validate if it meets the requirement

用stack

colon ['kəʊlən]

一条新的指令三种情况:①比stack的top指令多一个tab=>确保top的最后是冒号②与top相等③比top小,于是弹出所有的比当前指令缩进小的top

所以是

  1. 先判断stack是否为空,空的话要看新指令level是不是为0
  2. 看top最后是不是冒号,如果是看level是不是比top多一个
  3. 弹出所有比当前level大的top,弹完以后看当前level是不是等于top的level
  4. 最最最后check一下top的末尾是不是冒号结尾

用一个getlevel的函数计算tab(空格?) '/t'

Valid Python indentation。用stack写的,秒做,follow up问了个有没有办法优化。
实际上是因为我每次stack push的是line也就是每一行的string。
其实在过程中存string是因为要判断上一句是不是control statement。
所以我说了优化可以就存个line space的数,然后另外村是不是control statement。
我还特意问了能不能假设每一行结尾会不会有多余的space。他说可以忽略这个问题。记得检查第一行是不是valid。
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>

using namespace std;
int countIndent(string s) {
    int cnt = 0;
    while (s[cnt] == ' ') cnt++;
    return cnt;
}
bool validatePythonIndentationWrong(vector<string>& inputs) {
    stack<string> st;
    for (string s : inputs) {
        int indent = countIndent(s);
        if (st.empty()) {
            if (indent) {
                cout<<s<<1<<endl;
                return false;
            }
        }
        else if (st.top().back() == ':') {
                if (countIndent(st.top()) + 2 != indent) {
                    cout<<s<<2<<endl;
                    return false;
                }
        }
        else {
            while (indent < countIndent(st.top()))
                st.pop();
            if (countIndent(st.top()) != indent) {
                cout<<s<<3<<endl;
                return false;
            }
        }
        st.push(s);        
    }
    return (st.empty() || st.top().back() != ':');
}
bool validatePythonIndentation(vector<string> codes) {
    int last;
    for (int i = 0; i < codes.size(); i++) {
        int curr = 0;
        while (codes[i][curr] == '\t')curr++;
        bool flag = true;
        if (i == 0) {
            if (curr) flag = false;
        } else {
            if (codes[i - 1].back() == ':') {
                if (curr != last + 1) flag = false;
            }
            else if (last < curr) flag = false;
        }
        if (!flag) {
            cout<<codes[i]<<endl;
            return false;
        }
        last = curr;
    }
    if (codes.back().back() == ':') {
        cout<<codes.back()<<endl;
        return false;
    }
    return true;
}
int main(int argc, char *argv[]) {
    vector<string> s;
    s.push_back("def");
    s.push_back("abdc:");
    s.push_back("    bcc");
    s.push_back("    abc:");
    s.push_back("        def");
    s.push_back("        def");
    s.push_back("    bccv");
    cout<<validatePythonIndentation(s)<<endl;
}

results matching ""

    No results matching ""