我已经实现了Stock Span问题的代码。问题是变量 count 没有被永久改变,它保持为零。它仅在递归期间发生变化。我也做了计数静态。但同样的问题发生了。以下是代码。
public static void test(Stack s,int previous,int count)
{
if (!s.isEmpty())
{
int next = (int)s.pop();
if (previous > next)
{
count++;
// System.out.print(previous+" "+next+"===>"+count); // count is being changed here
}
System.out.println();
test( s,previous,count);
s.push(next);
}
}
public static void pan(Stack s, int [] array)
{
int count=0;
int i=array.length-1;
while (s.size()>1)
{
int previous = (int)s.pop();
test(s,previous,count);
array [i] = count+1;
i--;
count=0;
}
array [i] = 1;
}
public static void main (String [] args)
{
Stack s = new Stack();
s.push(10);s.push(20);s.push(5);s.push(5);s.push(10);
int [] array = new int [s.size()];
pan(s,array);
System.out.println(Arrays.toString(array));
}