O(n) one pass Java 94% fastest solution


  • 0
    A
    public class Solution {
        public String parseTernary(String expression) {
            
            int index = 0;
            int colonCount;
            while(index <= expression.length()) {
                if(index == expression.length() - 1 || expression.charAt(index + 1) == ':') {
                    return expression.charAt(index) + "";
                } else if(expression.charAt(index) == 'F') {
                    colonCount = 1;
                    index += 2;
                    while(colonCount > 0) {
                        if(expression.charAt(index) == ':') {
                            colonCount--;
                        } else if(expression.charAt(index) == '?') {
                            colonCount++;
                        }
                        index++;
                    }
                } else {
                    index += 2;
                }
            }
            return "";
        }
    }
    

Log in to reply
 

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