【剑指】48.最长不含重复字符的子字符串

题目描述

  • 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从'a'到'z'的字符。

算法分析

  • 动态规划,创建一个26大小的一维数组,用来存储上一次出现某个字符的索引。我们分情况讨论:设到第i个字符的最长不重复子字符串长度为f(i)
    (1)如果第i个字符之前没有出现过。f(i) = f(i-1)+1;
    (2)如果第i个字符之前出现过,又分两种情况:
            1)第i个字符和上一次出现的位置的距离d小于或等于目前的不重复子字符串的长度f(i-1)的时候,f(i) = d,意味着第i个字符出现两次所夹的字符中没有重复的字符。
            2)当d大于f(i-1)的时候,说明第i个字符上一次出现在最长子字符串之前,f(i) = f(i-1)+1
    时间复杂度O(n),空间复杂度O(1)

提交代码:

class Solution {
public:
	/* 动态规划 */
	int longestSubstringWithoutDuplication(string str)
	{
		if (str.empty())
			return 0;

		vector<int> position(26, -1);
		int currLen = 0, maxLen = 0;
		for (int i = 0; i < str.size(); ++i)
		{
			int index = str[i] - 'a';
			if (position[index] < 0 || (i - position[index]) > currLen)
				currLen += 1;
			else
				currLen = i - position[index];
			position[index] = i;
			if (currLen > maxLen)
				maxLen = currLen;
		}

		return maxLen;
	}

};

测试代码:

// ====================测试代码====================
void testSolution1(const string& input, int expected)
{
	Solution s;
	int output = s.longestSubstringWithoutDuplication(input);
	if (output == expected)
		std::cout << "Solution 1 passed, with input: " << input << std::endl;
	else
		std::cout << "Solution 1 FAILED, with input: " << input << std::endl;
}

void test(const std::string& input, int expected)
{
	testSolution1(input, expected);
	//testSolution2(input, expected);
}

void test1()
{
	const std::string input = "abcacfrar";
	int expected = 4;
	test(input, expected);
}

void test2()
{
	const std::string input = "acfrarabc";
	int expected = 4;
	test(input, expected);
}

void test3()
{
	const std::string input = "arabcacfr";
	int expected = 4;
	test(input, expected);
}

void test4()
{
	const std::string input = "aaaa";
	int expected = 1;
	test(input, expected);
}

void test5()
{
	const std::string input = "abcdefg";
	int expected = 7;
	test(input, expected);
}

void test6()
{
	const std::string input = "aaabbbccc";
	int expected = 2;
	test(input, expected);
}

void test7()
{
	const std::string input = "abcdcba";
	int expected = 4;
	test(input, expected);
}

void test8()
{
	const std::string input = "abcdaef";
	int expected = 6;
	test(input, expected);
}

void test9()
{
	const std::string input = "a";
	int expected = 1;
	test(input, expected);
}

void test10()
{
	const std::string input = "";
	int expected = 0;
	test(input, expected);
}

int main(int argc, char* argv[])
{
	test1();
	test2();
	test3();
	test4();
	test5();
	test6();
	test7();
	test8();
	test9();
	test10();

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81014023
今日推荐