Java Stack Solution - very easy to understand


  • 0
    F

    My solution is:

    1. put the number sequence in stack
    2. If the current char is 'I' or the iteration ends (means the decrease of this part ends), then pop up stack into result set until stack is empty.
    public int[] findPermutation2(String s) {
    	int[] res = new int[s.length() + 1];
    	int index = 0;
    
    	char[] cs = s.toCharArray();
    	
    	int seq = 1;
    	Deque<Integer> stk = new LinkedList<>();
    	stk.push(seq++);
    	for (int i = 0; i < cs.length; i++) {
    		if (cs[i] == 'I') {
    			while (!stk.isEmpty()) {
    				res[index++] = stk.pop();
    			}
    		}
    		stk.push(seq++);
    
    	}
    	while(!stk.isEmpty()){
    		res[index++]=stk.pop();
    	}
    	return res;
    }

Log in to reply
 

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