C# 力扣-514-自由之路

题目

在这里插入图片描述
在这里插入图片描述
正常解法

public static int FindRotateSteps(string ring, string key)
		{
			List<Dictionary<int, int>> res = new List<Dictionary<int, int>>();
			Dictionary<int, int> first = new Dictionary<int, int>();
			for (int i = 0; i < ring.Length; i++)
			{
				if (ring[i] == key[0])
				{
					int num = i + 1 > ring.Length - i + 1 ? ring.Length - i + 1 : i + 1;
					first.Add(i, num);
				}
			}
			res.Add(first);
			for (int i = 1; i < key.Length; i++)
			{
				Dictionary<int, int> temp = new Dictionary<int, int>();
				foreach (var item in res[i - 1])
				{
					for (int x = 0; x < ring.Length; x++)
					{
						if (ring[x] == key[i])
						{
							int max = item.Key > x ? item.Key : x;
							int min = item.Key > x ? x : item.Key;
							int lenA = max - min + 1;
							int lenB = ring.Length - max + min + 1;
							int len = lenA > lenB ? lenB : lenA;
							if (temp.ContainsKey(x))
							{
								if (item.Value + len > temp[x]) continue;
								temp[x] = item.Value + len;
							}
							else
								temp.Add(x, item.Value + len);
						}
					}
				}
				res.Add(temp);
			}
			int sum = int.MaxValue;
			foreach (var item in res[res.Count - 1])
			{
				if (item.Value < sum) sum = item.Value;
			}
			return sum;

		}

递归解法(欠缺优化)

public  class node
		{
			public char ch;
			public node before;
			public node next;
		}
		public static node creat(string str)
		{
			node first = new node();
			first.ch = str[0];
			node p = first;
			for (int i = 1; i < str.Length; i++)
			{
				node s = new node();
				s.ch = str[i];
				p.next = s;
				s.before = p;
				p = s;
			}
			p.next = first;
			first.before = p;
			return first;
		}
		public static int FindRotateSteps(string ring, string key)
		{
			node startnode = creat(ring);
			List<int> res = new List<int>();
			myfun(startnode, key, res);
			res.Sort();
			return res[0];


		}
		public static void myfun(node startnode,string key, List<int> res,int index = 0)
		{
			node b = startnode, n = startnode;
			int bnum = index, nnum = index;
			if (key.Length == 0)
			{
				res.Add(index);
				return;
			}
			while (b.ch != key[0])
			{
				b = b.before;
				bnum++;
			}
			while (n.ch != key[0])
			{
				n = n.next;
				nnum++;
			}
			nnum++;bnum++;
			string subkey = key.Substring(1);
			if (n != b)
			{					
				myfun(n, subkey, res, nnum);
				myfun(b, subkey, res, bnum);
			}
			else
			{
				if (bnum > nnum) myfun(n, subkey, res, nnum);
				else
					myfun(b, subkey, res, bnum);
			}
			
		}

要点说明

  • 递归算法,效率太低,以至于超时。
  • 递归算法写的时候没有考虑仔细,没必要用链表。
  • 正常解法
  • 若不存在相同的单词,则只需判断顺时针移动还是逆时针移动。
  • 若存在相同的单词,则上一次的位置会对下一次的位置造成影响。
  • 通过不同的位置移动到相同的位置,选择代价最小的,即可减少程序分支,增大效率。
  • 也不是那么困难,毕竟可以正常解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值