各种刷题笔记提高自己的code水平 demo

本文精选了多道经典的编程题目,并提供了详细的解题思路与代码实现,涵盖了数组、链表、二叉树、字符串处理及动态规划等多个方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:

设有n个正整数,将他们连接成一排,组成一个最大的多位整数。

如:n=3时,3个整数13,312,343,连成的最大整数为34331213。

如:n=4时,4个整数7,13,4,246连接成的最大整数为7424613。

解题思路 冒泡排序的应用,如果两个字符串的字典序 nums[j]+nums[j-1]大于nums[j-1]+nums[j] 此时就要交换nums[j]和nums[j-1]

python实现

while True:
    try:
        n=int(input())
        nums_strings=input().split()
        print(nums_strings)
        #print("".join(sorted(nums_strings,key=lambda x,y:-1 if x+y>y+x else 1)))
        #进行冒泡排序的方式
        for i in range(len(nums_strings)-1):
            for j in range(len(nums_strings)-1,i,-1):
                if(nums_strings[j]+nums_strings[j-1]>nums_strings[j-1]+nums_strings[j]):
                    nums_strings[j],nums_strings[j-1]=nums_strings[j-1],nums_strings[j]
        print("".join(nums_strings))
    except:
        break

C++实现代码:变形的冒泡排序的使用(对于会有溢出的数字,往往采用的是字符串或者是数组去表示)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(string x,string y){
    return x+y>y+x;
}
int main(){
    int n;
    while(cin>>n){
        vector<string>temp(n);
        for(int i=0;i<n;i++){
            cin>>temp[i];
        }
        sort(temp.begin(),temp.end(),compare);
        for(int i=0;i<n;i++){
            cout<<temp[i];
        }
        cout<<endl;
    }
    
    
}

2:将字符串进行反向输出:

python实现

mystring=input()
print(" ".join(mystring.split()[::-1]))

C++实现:通过借助stringstream 字符串流来实现;

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
void reverse(vector<string> &temp,string ss){
    stringstream scin;
    scin<<ss;
    string temps;
    while(scin>>temps){
        temp.push_back(temps);
    }
}
int main(){
    string mystring;
    getline(cin,mystring);
    vector<string> temp;
    reverse(temp,mystring);
    for(int i=temp.size()-1;i>0;i--){
        cout<<temp[i]<<' ';
    }
    cout<<temp[0]<<endl;
    
}

3:

首先将电话号码中的每个数字加上8取个位,然后使用对应的大写字母代替("ZERO", "ONE", "TWO", "THREE","FOUR", "FIVE", "SIX", "SEVEN","EIGHT", "NINE"), 然后随机打乱这些字母,所生成的字符串即为电话号码对应的分身。

思路根据特点统计出相应的字符串的个数,然后组合成变换后的数字,然后转换成变换前的数字(从小到大输出)

python实现

#统计出有多少个数据
def calculate(mystring):
    temp=[0]*10
    temp[0]=mystring.count("Z")
    temp[2]=mystring.count("W")
    temp[4]=mystring.count("U")
    temp[6]=mystring.count("X")
    temp[7]=mystring.count("S")-temp[6]
    temp[5]=mystring.count("V")-temp[7]
    temp[3]=mystring.count("R")-temp[4]-temp[0]
    temp[8]=mystring.count("G")
    temp[1]=mystring.count("O")-temp[0]-temp[2]-temp[4]
    temp[9]=mystring.count("I")-temp[6]-temp[5]-temp[8]
    return temp

n=int(input())
for i in range(n):
    mystring=input()
    res=""
    temp=calculate(mystring)
    for i, r in enumerate(temp):
        res+=r*str(i)
    ans=""
    for i in res:
        if(int(i)>=8):
            ans+=str(int(i)-8)
        else:
            ans+=str(int(i)+10-8)
    print("".join(sorted(ans)))


4:

水鲜花树python实现 判断一定范围内的水鲜化数

while True:
    try:
        begin,end=map(int,input().split())
        ans=[]
        for i in range(begin,end+1):
            temp=str(i)
            result=0
            for j in temp:
                result+=int(j)**3
            if(result==i):
                ans.append(i)
        if(len(ans)==0):
            print("no")
        else:
            print(" ".join(map(str,ans)))
    except:
        break

C++实现就不写了 思路比较简单的还是;


5:袋鼠过河问题:

一只袋鼠要从河这边跳到河对岸,河很宽,但是河中间打了很多桩子,每隔一米就有一个,每个桩子上都有一个弹簧,袋鼠跳到弹簧上就可以跳的更远。每个弹簧力量不同,用一个数字代表它的力量,如果弹簧力量为5,就代表袋鼠下一跳最多能够跳5米,如果为0,就会陷进去无法继续跳跃。河流一共N米宽,袋鼠初始位置就在第一个弹簧上面,要跳到最后一个弹簧之后就算过河了,给定每个弹簧的力量,求袋鼠最少需要多少跳能够到达对岸。如果无法到达输出-1

输入:

5
2 0 1 1 1

输出:

4

解题思路:动态规划问题,用dp[i]表示跳到i位置所需要的最小的跳数;dp[0]=0 dp[i+1]=min(dp[i+1],dp[i]+1)

python实现:

#动态规划的问题:
#python设置无穷大

num=int(input())
nums=[int(x)for x in input().split()]
#动态规划数组的定义
inf=float('inf')
dp=[inf]*(num+1)
dp[0]=0
for i in range(num):
    j=1
    while j<=nums[i] and i+j<=num:
        dp[i+j]=min(dp[i+j],dp[i]+1)
        j+=1
if(dp[num]!=inf):
    print(dp[num])
else:
    print(-1)

C++实现:

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<int> nums;
    for(int i=0;i<n;i++){
        int temp;
        cin>>temp;
        nums.push_back(temp);
    }
    vector<int> ans(n+1,10240);
    ans[0]=0;
    for(int i=0;i<n;i++){
        int j=1;
        while(j<=nums[i]&&(i+j)<=n){
            ans[i+j]=min(ans[i+j],ans[i]+1);
            j++;
        }
    }
    if(ans[n]!=10240){
        cout<<ans[n]<<endl;
    }
    else{
        cout<<-1<<endl;
    }
}

6:全排列的问题:给定一个数组求该数组的全排列问题:

其实这个问题不是全排列,是可以重复抽样的排列

下面才是全排列的实现方式:

void show(vector<vector<int>>& ans) {
	for (int i = 0; i < ans.size(); i++) {
		for (int j = 0; j < ans[i].size(); j++) {
			
			cout << ans[i][j];
		}
		
		cout << endl;
		cout << "hello" << endl;
	}
}
void printNQsort(vector<vector<int>> &all,vector<int> &ans, vector<int> & nums, int N, int index) {
	if (index == nums.size()-1) {
		all.push_back(ans);
		return;
	}
	for (int i = 0; i < nums.size(); i++) {
		ans[index + 1] = nums[i];
		printNQsort(all,ans, nums, N, index + 1);
	}
}
void find_path(vector<vector<int>>& ans, vector<int>& path, vector<int>nums, vector<bool>& flag, int index, int N) {
	if (path.size() == N) {
		ans.push_back(path);
		return;
	}
	for (int i = 0; i < N; i++) {
		if (flag[i] == false) {
			path.push_back(nums[i]);
			flag[i] = true;
			find_path(ans, path, nums, flag, index + 1, N);
			path.pop_back();
			flag[i] = false;
		}
	}
}
int main() {
	int N;
	cin >> N;
	vector<int>nums(N, 0);
	int temp;
	for (int i = 0; i < N; i++) {
		cin >> temp;
		nums[i] = temp;
	}
	vector<int> ans;
	vector<vector<int>> all;
	//下面是真正的全排列的代码
	vector<bool> flag(N, false);
	find_path(all, ans, nums,flag, 0, N);

	show(all);
	system("pause");
}

递归的方式来实现

C++实现:

#include<iostream>
#include<vector>
#include<string>
#include<cmath>
using namespace std;
//实现的功能是打印出数组的全排列 递归实现
void printNQsort(vector<int> &ans, vector<int> & nums, int N, int index) {
	if (index==N - 1) {
		for (int i = 0; i < N; i++) {
			cout << ans[i];
		}
		cout << endl;
		return;
	}
	for (int i = 0; i < N; i++) {
		ans[index + 1] = nums[i];
		printNQsort(ans, nums,N, index + 1);
	}

}

int main() {
	int N;
	cin >> N;
	vector<int>nums(N, 0);
	int temp;
	for (int i = 0; i < N; i++) {
		cin >> temp;
		nums[i] = temp;
	}
	vector<int> ans(N, 0);
	for (int i = 0; i < N; i++) {
		
		ans[0] = nums[i];
		printNQsort(ans,nums, N, 0);

	}
	system("pause");
}

python实现

#全排列的实现
def quanpailie(ans,nums,N,index):
    if(index==N-1):
        print("".join(map(str,ans)))
        return
    else:
        for item in nums:
            ans[index+1]=item
            quanpailie(ans,nums,N,index+1)

N=int(input())
mylist=[int(item) for item in input().split()]

ans=[0]*N
for num in mylist:
    ans[0]=num
    quanpailie(ans,mylist,N,0)

全排列的应用:

打印从1到最大的N位数:由于N的数值可能很大,所以直接输出肯定会有溢出的情况发生;

void printNQsort(vector<int> &ans, int N, int index) {
	if (index==N-1) {
		for (int i =0; i<N; i++) {
			cout << ans[i];
		}
		//cout << endl;
		return;
	}
	for (int i = 0; i <=9; i++) {
		ans[index + 1] = i;
		printNQsort(ans,N, index + 1);
	}

}
int main() {
	int N;
	cin >> N;
	vector<int> ans(N, 0);
	for (int i = 0; i < 10; i++) {		
		ans[0] =i;
		printNQsort(ans, N, 0);
	}
	system("pause");
}

python实现:

#全排列法实现输出0-N的N位整数;
def quanpailie(ans,N,index):
    if(index==N-1):
        num_string="".join(map(str,ans))
        #print(type(num_string))
        i=0
        while(num_string[i]=='0' and i<len(num_string)-1):
            i+=1
        print(num_string[i:])
        return
    else:
        for item in range(10):
            ans[index+1]=item
            quanpailie(ans,N,index+1)
N=int(input())
ans=[0]*N
for num in range(10):
    ans[0]=num
    quanpailie(ans,N,0)

 

7:删除单个链表,时间复杂度为O(1)的情况下:

单纯的删除链表的时间复杂度为O(n) 不保留相应的重复结点

C++实现

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if(pHead==NULL){
            return pHead;
        }
        ListNode* pre=NULL;
        ListNode* curr=pHead;
        //ListNOde* Next=pHead->next;
        while(curr!=NULL){
            ListNode *Next=curr->next;
            bool needDel=false;//表示当前节点是否应该删除
            if(Next!=NULL&&curr->val==Next->val){
                needDel=true;
            }
            if(!needDel){
                pre=curr;
                curr=Next;//将节点后移
            }
            else{
                int tempval=curr->val;
                ListNode *toDelNode=curr;
                while(toDelNode!=NULL&&toDelNode->val==tempval){
                    Next=toDelNode->next;//指向下一个结点;
                    delete toDelNode;
                    toDelNode=NULL;
                    toDelNode=Next;
                }
                if(pre==NULL){
                    pHead=Next;//pHead=toDelNode;
                }
                else{
                    pre->next=Next;
                }
                curr=Next;
            }
        }
        return pHead;
    }
};

python实现:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if(pHead==None):
            return pHead
        preNode=ListNode(-1)
        preNode.next=pHead
        anNode=preNode
        currNode=pHead
        while(currNode!=None):
            Next=currNode.next
            needDel=False
            if(Next!=None and Next.val==currNode.val):
                needDel=True
            if(needDel==False):
                preNode=currNode
                currNode=Next
            else:
                temp=currNode.val#保存住当前的值;
                needDel=currNode
                while(needDel!=None and needDel.val==temp):
                    Next=needDel.next
                    del needDel
                    needDel=Next
                preNode.next=Next
                currNode=Next
        return anNode.next


8.表示数值的字符串: 指针的终极使用;

C++实现

class Solution {
public:
    bool isNumeric(char* string)
    {
        //使用C字符串的形式 来表示 指针的终极应用
        if(string==NULL){
            return false;
        }
        if(*string=='+'||*string=='-'){
            ++string;//指向下一个地址值
        }
        scanNum(&string);
        if(*string=='\0'){
            return true;//表示只有数据
        }
        if(*string=='.'){ //处理小数
            string++;
            if(*string=='\0'){//小数点后面没有数 
                return false;
            }
            scanNum(&string);
            if(*string=='\0'){//小数点后面只有数字
                return true;
            }
            else if(*string=='e'||*string=='E'){
                string++;
                return scanExp(&string);
            }
        }
        if(*string=='e'||*string=='E'){
            string++;
            return scanExp(&string);
        }
        return false;
    }
    void scanNum(char** string){
        while(**string!='\0'&&**string>='0'&&**string<='9'){
            ++(*string);
        }
    }
    bool scanExp(char** string){
        if(**string=='\0'){
            return false;
        }
        if(**string=='+'||**string=='-'){
            ++(*string);
            if(**string=='\0'){
                return false;
            }
        }
        scanNum(string);
        if(**string=='\0')
            return true;
        else
            return false;
        return false;
    }
};

python实现直接使用正则表达式就可以了:


9:调整数组元素的顺序,使得数组中的元素奇数位于偶数的前面

C++实现:

class Solution {
public:
    void reOrderArray(vector<int> &array) {
        //采用双指针的方式来进行改变相应的数组中的元素
        int left=0;
        int right=array.size()-1;
        while(left<right){
            if(array[left]%2==0&&array[right]%2==1){
                swap(array[left],array[right]);
                left++;
                right--;
            }
            else if(array[left]%2==1){
                left++;
            }
            else{
                right--;
            }
        }
        //不考虑顺序关系时使用这种方法 两个指针交换的方式;
    }
};

python实现:

def reOrderArray(self, array):#使用空间复杂度为O(n)的算法
        # write code here
        nums1=[]
        nums2=[]
        for item in array:
            if(item%2==0):
                nums2.append(item)
            else:
                nums1.append(item)
        nums1.extend(nums2)
        return nums1


10:求解链表中的倒数第k个结点

C++实现,注意边界条件的问题

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
           ListNode *first=pListHead;
           ListNode *second=pListHead;
           int i=0;
           while(second!=NULL&&i<k){
               second=second->next;
               i++;
           }
           if(second==NULL&&i<k){
               return NULL;
           }
           if(second==NULL){
               return first;
           }
           while(second!=NULL){
               second=second->next;
               first=first->next;
           }
           return first;
    }

python实现:可以直接上面的思路两个指针的方式



11:反转链表:

C++实现:

ListNode* ReverseList(ListNode* pHead) {
        //通过三个指针来反转链表
        ListNode *pre=NULL;
        ListNode *curr=pHead;
        if(curr==NULL){
            return pHead;
        }
        ListNode *Next=curr->next;
        while(Next!=NULL){
            ListNode *temp=Next->next;
            curr->next=pre;
            Next->next=curr;
            pre=curr;
            curr=Next;
            Next=temp;
        }
        return curr;
    }


12:合并两个排序的链表:

C++实现:

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        //开辟一个新的空间,空间复杂度为O(n)
        //使用递归的写法:
        if(pHead1==NULL){
            return pHead2;
        }
        if(pHead2==NULL){
            return pHead1;
        }
        ListNode *ans=NULL;
        if(pHead1->val<pHead2->val){
             ans=pHead1;
             ans->next=Merge(pHead1->next,pHead2);
        }
        else{
            ans=pHead2;
            ans->next=Merge(pHead2->next,pHead1);
        }
        return ans;
    }


python 实现:

def Merge(self, pHead1, pHead2):
        # write code here
        if(pHead1==None):
            return pHead2
        if(pHead2==None):
            return pHead1
        node=ListNode(-1)
        if(pHead1.val<pHead2.val):
            node=pHead1
            node.next=self.Merge(pHead1.next,pHead2)
        else:
            node=pHead2
            node.next=self.Merge(pHead2.next,pHead1)
        return node


13:求一棵树的镜像:

C++实现

void Mirror(TreeNode *pRoot) {
        //之前做过的题是交换二叉树的左右子树
        /*
        if(pRoot==NULL){
            return ;
        }
        if(pRoot->left==NULL&&pRoot->right==NULL){
            return;
        }
        else{
            swap(pRoot->left,pRoot->right);
        }*/
        //还是使用递归的方式来实现
        if(pRoot==NULL){
            return;
        }
        if(pRoot->left==NULL&&pRoot->right==NULL){
            return;
        }
        swap(pRoot->left,pRoot->right);
        if(pRoot->left){
            Mirror(pRoot->left);
        }
        if(pRoot->right){
            Mirror(pRoot->right);
        }
    }

python实现:

class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if(root==None):
            return
        if(root.left==None and root.right==None):
            return
        root.left,root.right=root.right,root.left
        if(root.left!=None):
            self.Mirror(root.left)
        if(root.right!=None):
            self.Mirror(root.right)


14:判断一棵树是否是对称树:

C++实现

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
        //创建两个树进行比较
        return isbool(pRoot,pRoot);
    }
    bool isbool(TreeNode *root1,TreeNode* root2){
        if(root1==NULL&&root2==NULL){
            return true;
        }
        if(root1==NULL||root2==NULL){
            return false;
        }
        if(root1->val!=root2->val){
            return false;
        }
        return isbool(root1->left,root2->right)&&isbool(root1->right,root2->left);
    }

};


15:包含一个可以去到最小值的栈,要求时间复杂度为O(1)

解题思路就是用空间来换取时间,通过构建一个新的数据栈

数据栈中的栈顶始终是栈中的最小值;

C++实现:

class Solution {
public:
    void push(int value) {
        ss.push(value);
        if(temp.size()==0||value<temp.top()){
            temp.push(value);
        }
        else{
           temp.push(temp.top()); 
        }
       }
    void pop() {
        ss.pop();
        temp.pop();
    }
    int top() {
        return ss.top();
    }
    int min() {
        return temp.top();
    }
    stack<int> ss;
    stack<int> temp;//使用一个辅助栈来保存相应的数据
};

16:二叉树中某一路径和为某一值的路径,

递归和回溯解法(不应该不熟悉啊)

C++实现(之前是数组,现在是树而已)

vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            //递归和回溯的方法来进行解题
        vector<vector<int>> ans;
        if(root==NULL){
            return ans;
        }
        vector<int> path;
        int current=0;
        dfs(ans,path,root,expectNumber,current);
        return ans;
    }
    void dfs(vector<vector<int>> &ans, vector<int>& temp,TreeNode* root,int expectNumber,int current){
        current+=root->val;
        temp.push_back(root->val);
        if(current==expectNumber&&root->left==NULL&&root->right==NULL){
            ans.push_back(temp);
            return;
        }
        if(root->left!=NULL){
            dfs(ans,temp,root->left,expectNumber,current);
            temp.pop_back();
        }
        if(root->right!=NULL){
            dfs(ans,temp,root->right,expectNumber,current);
            temp.pop_back();
        }
    }


17:字符串的全排列,含有重复字符的情况下,一开始想到的是使用递归和回溯算法来实现相应的排序,但是对于重复字符串存在问题

所以使用剑指offer中的方式来实现

C++实现

vector<string> Permutation(string str) {
        vector<string> ans;
        if(str.size()==0){
            return ans;
        }
        detail_permutation(ans,str,0,str.size());
        map<string,int> mymap;
        for(int i=0;i<ans.size();i++){
            mymap[ans[i]]+=1;
        }
        vector<string> result;
        map<string,int>::iterator it=mymap.begin();
        for(it;it!=mymap.end();it++){
            result.push_back(it->first);
        }
        return result;
    }
   void  detail_permutation(vector<string> &ans,string &str,int index,int N){
       if(index==N){
           ans.push_back(str);
           return;
       }
       for(int i=index;i<N;i++){
           swap(str[index],str[i]);
           detail_permutation(ans,str,index+1,N);
           swap(str[index],str[i]);
       }
   }


python实现: 需要注意的是python中的字符串是不可变的类型不能进行赋值操作;所以要先转换为字符列表;

class Solution:
    def Permutation(self, ss):
        # write code here
        ans=[]
        if(len(ss)==0):
            return ans
        ss_list=[]
        for char in ss:
            ss_list.append(char)
        self.mypermulate(ans,ss_list,0,len(ss))
        return ans
    def mypermulate(self,ans,ss,index,N):
        if(index==N):
            ans.append(''.join(ss))
            return
        else:
            for i in range(index,N):
                ss[i],ss[index]=ss[index],ss[i]
                self.mypermulate(ans,ss,index+1,N)
                ss[i],ss[index]=ss[index],ss[i]

18:把数字翻译成字符串的方式:

使用两种方式:一种是递归的方式,另外一种是动态规划方式;

C++动态规化

int main() {
	string ss;
	cin >> ss;
	int size = ss.size();
	if (size == 0) {
		cout << 0 << endl;
	}
	vector<int> ans(size + 1, 0);
	ans[size] = 1;
	ans[size - 1] = 1;
	for (int i = size - 2; i >= 0; i--) {
		//动态规划寻找相应的数值
		if (ss[i] - '0' >= 1 && ss[i] - '0' <= 2&& ss[i + 1] - '0' <= 5&&ss[i+1]-'0'>=0) {
			ans[i] = ans[i + 1] + ans[i + 2];
		}
		else if (ss[i] - '0' == 1 && ss[i + 1] - '0' <= 9 && ss[i + 1] - '0' >= 0) {
			ans[i] = ans[i + 1] + ans[i + 2];
		}
		else {
			ans[i] = ans[i + 1];
		}

	}
	cout << ans[0] << endl;
	system("pause");

}


19:礼物的最大价值的实现:

还是使用动态规划的思想来实现:

int main() {
	int m, n;
	cin >> m >> n;
	vector<vector<int>> nums(m, vector<int>(n, 0));
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cin >> nums[i][j];
		}
	}
	//使用二维数组来保存相应的结果;
	vector<vector<int>> temp(m, vector<int>(n, 0));
	temp[m - 1][n - 1] = nums[m - 1][n - 1];
	for (int i = m - 2; i >= 0; i--) {
		temp[i][n - 1] = temp[i+1][n - 1] + nums[i][n - 1];
	}
	for (int i = n - 2; i >= 0; i--) {
		temp[m - 1][i] = temp[m - 1][i + 1] + nums[m - 1][i];
	}
	for (int i = m - 2; i >= 0;i--) {
		for (int j = n - 2; j >= 0; j--) {
			temp[i][j] = nums[i][j] + max(temp[i + 1][j], temp[i][j + 1]);
		}
	}
	cout << temp[0][0];
	system("pause");

}

20:

最长不含重复字符的子字符串(最长无重复字符串);

int max(vector<int > ans) {
	int Max = 0;
	for (int i = 0; i < ans.size(); i++) {
		Max = max(ans[i], Max);
	}
	return Max;
}
int main() {
	string ss;
	cin >> ss;
	int size = ss.size();
	vector<int> ans(size, 0);
	vector<int> flag(256, -1);
	//设定一个标志 用来表示字符串是否出现过 等信息
	ans[0] = 1;
	flag[ss[0] - 'a'] = 0;//0表示出现的索引
	for (int i = 1; i < size; i++) {
		if (flag[ss[i] - 'a'] == -1) {
			ans[i] = ans[i - 1] + 1;
			flag[ss[i] - 'a'] = i;
		}
		else {
			int d = i - flag[ss[i] - 'a'];
			if (d <=ans[i - 1]) {
				ans[i] = d;
				//将数据更新为i
				flag[ss[i] - 'a'] = i;
			}
			else {
				ans[i] = ans[i - 1]+1;
				flag[ss[i] - 'a'] = i;
			}
		
		}
	}
	cout << max(ans);
	system("pause");

}

python 实现:

while True:
    try:
        mystring=input()
        result=[-1]*256
        ans=[0]*len(mystring)
        ans[0]=1
        for i in range(2,len(mystring)):
            if(result[ord(mystring[i])-ord('a')]==-1):
                ans[i]=ans[i-1]+1
                result[ord(mystring[i])-ord('a')]=i
            else:
                d=i-result[ord(mystring[i])-ord('a')]
                if(d>ans[i-1]):
                    ans[i]=ans[i-1]+1
                    result[ord(mystring[i])-ord('a')] = i
                else:
                    ans[i]=d
                    result[ord(mystring[i])-ord('a')] = i
        print(max(ans))
    except:
        break





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值