筆試-最長不含重複的子符子串

題目描述:
請從字符串中找出一個最長的不包含重複字符的子字符串,計算該最長子字符串的長度。假設字符串中只包含’a’~'z’的字符。

輸入描述:
輸入的第一行爲一個字符串

輸出描述:
輸出一個整數表示最長不含重複子字符串的長度

#include<iostream>
#include<string.h>
using namespace std;

int longestSubLength(string input);

int main()
{
	string input;
	cin>>input;
	int result=longestSubLength(input);	
	printf("%d",result);
} 

int longestSubLength(string input)
{
	/**
	  * subLength用於統計當前子串長度
	  * maxLength用於統計最長子串長度 
	*/ 
	int subLength=0,maxLength=0,arr[26],strLength=input.length();
	memset(arr,-1,sizeof(arr)); //存放當前字符出現的最新位置 
	for(int index=0;index<strLength;index++){
		int preIndex=arr[input[index]-'a'];
		if(preIndex<0||index-preIndex>subLength){ //當該字符從未出現或者上一次出現位置大於當前子串長度說明該子串長度加一 
			subLength++;
		}else{
			if(subLength>maxLength){
				maxLength=subLength;
			}
			subLength=index-preIndex;
		}
		arr[input[index]-'a']=index; //更新字符最新位置 
	}
	
	if(subLength>maxLength){ //更新最後一個子串的長度 
		maxLength=subLength;
	}
	
	return maxLength;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章