给定序列,求所有正确的出栈序列

using System;
using System.Collections.Generic;
namespace 所有出栈可能
{
	class Program
	{
		public static void Myfun(string str,List<string> res)
		{
			string temp = "";
			Produce(str, temp, res);
			Distinct(res);
			
			for (int i = 0; i < res.Count; i++)
			{
				Stack<char> S = new Stack<char>();
				for (int j = 0,index=0; j < str.Length; j++)
				{
					S.Push(str[j]);
					while (S.Count>0&&S.Peek() == res[i][index])
					{
						S.Pop();
						index++;
					}
				}
				if (S.Count > 0) res.RemoveAt(i--);
			}
		}
		static void Distinct(List<string> res)
		{
			for (int i = 0; i < res.Count-1; i++)
			{
				for (int j = i+1; j < res.Count; j++)
				{
					if (res[i] == res[j])
						res.RemoveAt(j--);				
				}
			}
		}
		static void Produce(string str,string temp ,List<string> res)
		{
			if (temp.Length == str.Length)
			{
				res.Add(temp);
				return;
			}
			for (int i = 0; i < str.Length; i++)
			{
				temp += str[i];
				Produce(str, temp, res);
				temp = temp.Remove(temp.Length - 1);
			}
		}
		static void Main(string[] args)
		{
			string str = Console.ReadLine();
			List<string> res = new List<string>();
			Myfun(str, res);
			foreach (var item in res)
			{
				Console.WriteLine(item);
			}
			Console.WriteLine(res.Count);
		}
	}
}

几点说明

  1. 出栈特点:当入栈为有序时,出栈的大数后面比它小的数一定是降序排列。否者不合法,
  2. 常规特点:当判断一个序列是否是正确是出栈顺序,先入栈一个元素,然后判断栈顶是否和出栈序列值相同,否者继续入栈,直到与之匹配。然后一直出栈,直到不匹配。再次继续之前的操作直到,入栈序列为空。
  3. 数列去重:值去重,对于存储对象的数列无效
using System.linq;
List<int> tt=new List<int>(){1,2,2,1};
tt=tt.Distinct().toList();
List<int> tt=new List<int>(){1,2,2,1};
tt=new HashSet<int>(tt).toList();
  1. 如果是对象,则利用存储对象的值转字符串或直接对象的值进行比较,然后RemoveAt()
static void Distinct(List<string> res)
		{
			for (int i = 0; i < res.Count-1; i++)
			{
				for (int j = i+1; j < res.Count; j++)
				{
					if (res[i] == res[j])
						res.RemoveAt(j--);				
				}
			}
		}

小知识点-给编辑基础差的看

  1. && :逻辑与
    当前面的条件判断为false时,后面的条件就不再判断。
S.Count>0&&S.Peek() == res[i][index]

这里这是因为如此才能这么写,否者:当完全匹配时,栈顶为空,res[i][index]数组越界

  1. j- - ;
    j使用之后,数量减一。
if (res[i] == res[j])
res.RemoveAt(j--);
//if (res[i] == res[j]) res.RemoveAt(j--);  这样代码的可读性会更强					
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值