介绍

有的时候我们需要找到当前元素上一次出现时的索引,例如abcdadv第二个a出现时候,上一个a的索引为0(这里n是从0开始的)。

代码

	string s = "abcdadv";
	int last[1000];
	memset(last, 0, sizeof last);
	
	// 这是为了将s的索引从1开始的。
	s = ' ' + s;
	
	// 如果是第一次出现那么last就是0
	for (int i = 1; i < (int)s.size(); i ++ )
	{
		cout << last[s[i] - 'a'] << ' ';
		last[s[i] - 'a'] = i;
	}