简体   繁体   中英

Time complexity of this while loop:

What is the time complexity of this loop since it does not iterate by 1:

while (parser.hasNext())
            {
                token = parser.next();

                if (isOperator(token))
                {
                    op2 = (String)(stack.pop());
                    op1 = (String)(stack.pop());
                    result = evaluateSingleOperator(token.charAt(0), op1, op2);
                    stack.push(result);
                }
                else
                    stack.push(token);
            }

            return result;

Would it be O(n) because if there are 5 elements, hello, so the statements inside the loop will run 5 times?

Assuming typical semantics for most of your operations, and assuming that evaluateSingleOperator(char tokenChar, String op1, String op2) is O(|op1| + |op2|) and returns a string representation of a result with the length of the result being O(|op1| + |op2|), then this actually has complexity O(n^2).

Consider for example this working on the input: 10*10*10*10*10*10*....*10

Repeat the multiplication a few hundred times (so result does not just fit in a simple Integer or Long value). Then your evaluateSingleOperator(...) invocations will grow linearly with the length of the input.

The parsing process itself will only require O(n) iterations, and you will only invoke evaluateSingleOperator O(n) times, but in order to insure that the total operation time is O(n), you need to know that evaluateSingleOperator requires at most O(1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM