// 面试题48:最长不含重复字符的子字符串 // 题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子 // 字符串的长度。假设字符串中只包含从'a'到'z'的字符。 #include <string> #include <iostream> // 方法一:蛮力法 //不想说话 // 方法一:动态规划 int longestSubstringWithoutDuplication_2(const std::string& str) { int curLength = 0;//记录当前长度 int maxLength = 0;//记录最大长度 int* position = new int[26];//检测26个字母上次出现在字符串下标,没有用过为-1 for (int i = 0; i < 26; ++i) position[i] = -1; for (int i = 0; i < str.length(); ++i) { int prevIndex = position[str[i] - 'a']; if (prevIndex < 0 || i - prevIndex > curLength)//如果这个值之前没有被用过,或者用过但是二者相同字符的距离比当前记录的长度要大(这说明这个字符不再当前统计的范围内) ++curLength; else { if (curLength > maxLength) maxLength = curLength; curLength = i - prevIndex;//否则将二者相同字符的距离替换当前记录的长度 } position[str[i] - 'a'] = i;//记录这个字符的位置为i } if (curLength > maxLength)//记录到结束了,要比较一下最后一段的长度是否是最长的 maxLength = curLength; delete[] position; return maxLength; } // ====================测试代码==================== void testSolution2(const std::string& input, int expected) { int output = longestSubstringWithoutDuplication_2(input); if (output == expected) std::cout << "Solution 2 passed, with input: " << input << std::endl; else std::cout << "Solution 2 FAILED, with input: " << input << std::endl; } void test(const std::string& input, int 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(); system("pause"); return 0; }