Validate Python
1. 刚开始不能缩进
2. control block 的下一行要缩进
3. 缩进要一样
The input is String[], each line is a string. if it's valid,
return -1, otherwise return the line number.
follow up1: what is the last line is control block?
follow up2: what if there is comment line (" #").
/**
 * Created by 1000132937 on 3/27/2018.
 */
import java.util.Stack;

public class ValidatePython {

        public static boolean identification(String[] strs) {
            if (strs == null || strs.length == 0)   return true;
            if (countTab(strs[0]) != 0)     return false;
            Stack<Integer> stack = new Stack<>();
            stack.push(0); // the first line without indentation
            for (int i = 1; i < strs.length; i++) {
                if (strs[i].startsWith("#")) {
                    continue;
                }
                int cur = countTab(strs[i]);
                // if the previous line ends with:, meaning the next line need indentation , indentation is longer than the previous line
                if (strs[i-1].charAt(strs[i-1].length()-1) == ':' || (strs[i - 1].contains(":") && strs[i - 1].contains("#"))) {
                    if (cur <= stack.peek())   return false;
                } else {
                    //if in the same block, cur == stack.peek()
                    // if start a new block, cur < stack.peek()
                    if (cur > stack.peek())     return false;
                    while (!stack.isEmpty() && stack.peek() > cur) {
                        // if this line start a new block until stack.peek() <= cur
                        stack.pop();
                    }
                    if (stack.peek() != cur)    return false;
                }
                stack.push(cur);
            }
            return true;
        }
        public static int countTab(String s) {
            char[] arr = s.toCharArray();
            int cnt = 0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == ' ')     cnt++;
                else    break;
            }
            return cnt;
        }
        public static void main(String[] args) {
            String[] strs = {"def function():",
                    "  print(\"Hello world\")",
                    "  print(\"Hello world\")",
                    "  if i==1:",
                    "    print(\"asdf\")"};
            System.out.print(identification(strs));
        }

}

results matching ""

    No results matching ""