趋势科技2011校园招聘的一道编程笔试题
题目:编写一个函数int search(char *text),text为输入的字符串,从字符串中找出一个最长的不含重复字符的子字符串,例如“axdbx”,返回4,子字符串为“axdb”,而“axdbxce”,返回5,子字符串为“dbxce”。
以下是我的答案,当然,较当时答题时的答案少有改动,但思路是一样的,毕竟答题时没有环境让我去debug。该算法时间复杂度为O(n)。并且不需要反复重置pos数组,每次访问到重新赋值即可。
下载: search.cpp
- #include <iostream.h>
- #include <string.h>
- int search(char *text)
- {
- int pos[256]; //用于记录字符最近一次出现的位置,使用ASC码做索引
- int maxL = 0; //记录最大长度
- int start = 0; //记录连续字符串的起始位置
- int end = strlen(text), i, tL; //end为字符串text上界
- for (i=0; i<128; i++) pos[i] = -1; //为每个字符初始化位置
- for (i=0; i<end; i++) //遍历字符串
- {
- int index = text[i]; //得到当前字符索引
- if (pos[index] >= start) //当前字符在起始位置之后出现过,则出现重复
- {
- tL = i - start; //计算长度
- if (tL > maxL) maxL = tL; //若大于maxL,则记录
- start = pos[index] + 1; //重置start位置,为重复的字符之后一个位置
- }
- pos[index] = i; //记录当前字符位置
- }
- //末尾处理
- tL = i - start;
- if (tL > maxL) maxL = tL;
- return maxL;
- }
- void main()
- {
- char a[]="xabc123eDd56xesdADBfjkg";
- cout<<search(a)<<endl;
- }
Joke.li 原创
转载请注明出处
0 Comments until now
添加评论 Add your comments!