Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have to use a stack for this. </p> <p>Suppose the string is <code>{{1,1},2,{1,1}}</code>.</p> <pre><code>Step 1: Go through the string to determine its depth. </code></pre> <p>You can do this by initializing variables <code>depth =0</code> and <code>maxdepth=depth</code>; Everytime you encounter a '{' increment <code>depth</code> and if <code>depth&gt;maxdepth</code>, <code>maxdepth=depth</code>. If you encounter a '}', decrement <code>depth</code>. </p> <p>The final value of <code>maxdepth</code> will be the depth of the string. In this case <code>maxdepth=2</code>;</p> <pre><code>Step 2: Declare an array items_depth to the depth given by maxdepth. Integer[] items_depth = new Integer[maxdepth+1]; </code></pre> <p><code>items_depth</code> gives the number of items at any depth. Initialize all the elements in <code>items_depth</code> to 0. (Initially there are zero items at any depth). I assume 0 depth as well. So, for depth 2 there will be items at three depths 0,1,2.</p> <pre><code>Step 3: Go through the string again from left to right int depth =0; Stack&lt;Integer&gt; stack = new Stack&lt;Integer&gt;(); while(there are characters in the string) { char i = current character; if(i=='{') { depth++; } if(i is an integer) { items_depth[depth]++; stack.push(Integer.parseInt(i)); } if(i==',') { continue; } if(i=='}') { int temp= items_depth[depth]; int temp_depth = depth; depth--; int temp_sum=0; for(int i=1;i&lt;=items_depth[temp_depth] &amp;&amp; items_depth[temp_depth]&gt;0;i++) { temp_sum+=stack.pop(); } items_depth[temp_depth]=0; stack.push(temp_sum); item_depth[depth]++; } } return stack.pop(); </code></pre> <p>The last item popped from the stack will be the sum of the term with the depths as weight. I assumed a single character int. You have to modify the code to accomodate other ints</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload