CareerCup Find lexicographic minimum in a circular array 循环数组字典序

本文介绍了一个寻找给定字符串中字典序最小循环子串的有效算法。该算法通过将输入字符串拼接两次并进行一次遍历,实现O(n)的时间复杂度。文章附带了完整的C++代码实现。

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

Write the code to find lexicographic minimum in a circular array, e.g. for the array 

 

BCABDADAB, the lexicographic mininum is ABBCABDAD

 

------------------------------------------------------------------------------------

It's a nice problem!

Here is a O(n) solution : 
We concat the string twice, then browse the string from left to right, 
keeping the the start position of the current answer seen so far. 
When we see a letter that would possibly be the start pos of a new answer, we do 
not update it yet, instead we keep an offset that defines the size of the prefix 
that has been checked for comparison of the current best answer and the possible 
new answer. 

 

#include<iostream>
#include<string>
 
std::string lex_min(const std::string&);
 
int main() {
    
    std::cout<<lex_min("BCDEBCDBCC");
    
    return 0;
}

std::string lex_min(const std::string& str) { 
    
    int size = str.size(); 
    std::string input = str + str; 
     
    int offset = 0; 
    int answer = -1; 
     
    for (int i = 0; i < size * 2; i++) { 
        if (answer == -1) 
        { 
            // First character 
            answer = i; 
        } 
        else if (input[i] < input[answer]) { 
            // We definitely have a new answer here 
            answer = i; 
            // Reset the offset for future tie 
            offset = 0; 
        } 
        else if (input[i] == input[answer + offset]) { 
            // We might have another answer here 
            // move the offset forward 
            offset++; 
        } 
        else if (input[i] < input[answer + offset]) { 
            // we have found something even better 
            // than what we had before 
            // Set marker for new answer 
            answer = i - offset; 
            offset = 0; 
            if(input[i] == input[answer]) /* THIS IS THE CORRECTION*/
                offset=1;
        } 
        else { 
            offset = 0; 
        } 
    } 
     
    return input.substr(answer, size); 
    
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值