LeetCode and my own PC give different results! :(


  • 0
    L

    My solution is as below. Let the input be "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext". LeetCode gives 32 after execution, but I got 20 when running on my own computer. Any one can knows the reason? Thanks!
    '''
    class Solution {

    public int lengthLongestPath(String input) {
    	int n = input.length();
    	int p = 0, q = 0;
    	String seg = "";
    	String[] name = new String[] { "" };
    	int maxlen = 0;
    	Stack<String> stack = new Stack<>();
    	int stacklen = 0;
    	while (p < n) {
    		q = input.indexOf("\\n", p + 1);
    		seg = q == -1 ? input.substring(p, n) : input.substring(p, q);
    		int lv = level(seg, name);
    		while (!stack.isEmpty() && lv <= stack.size() - 1) {
    			String dir = stack.pop();
    			stacklen -= dir.length() + 1;
    		}
    		if (name[0].contains(".")) {
    			maxlen = Math.max(maxlen, stacklen + name[0].length());
    		} else {
    			stack.push(name[0]);
    			stacklen += name[0].length() + 1;
    		}
    		p = q == -1 ? n : q;
    	}
    	return maxlen;
    }
    
    private int level(String seg, String[] name) {
    	if (seg.equals("") || seg.charAt(0) != '\\') {
    		name[0] = seg;
    		return 0;
    	}
    	int lv = 0;
    	int p = 2;
    	while (seg.charAt(p) == '\\') {
    		lv++;
    		p += 2;
    	}
    	name[0] = seg.substring(p);
    	return lv;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.