zoukankan      html  css  js  c++  java
  • Lexicographical minimum in a String

    Problem: Given a string, find the lexicographical minimum string keeping the order of alphabets same as the original string.

    For example:

    Given StringLexicographical Minimum
    DABC ABCD
    ABCD ABCD
    CABABC ABABCC
    ABABCABA ABAABABC




    Solution: This can be done in O(n) by the following code, 学会操作字符串: 

    static String lexMin(String str) 
        { 
            String str2 = str + str; 
     
            int offset = 0; 
            int answer = 0; 
     
            for (int i = 1; i < str2.length(); i++) 
            { 
                if (str2.charAt(i) < str2.charAt(answer)) 
                { 
                    // New lexicographical minimum found.
                    // Reset all parameters here.
                    answer = i; 
                    offset = 0; 
                } 
                else if (str2.charAt(i) == str2.charAt(answer + offset)) 
                { 
                    // Keep moving the offset till this new string matches the previous answer
                    offset++; 
                } 
                else if (str2.charAt(i) < str2.charAt(answer + offset)) 
                { 
                    // In the new match, some character is found which is lower 
                    // than the character at same offset in the previous answer.
                    // So new answer becomes the lexicographical minimum, discard 
                    // the previous answer in favor of the new answer.
                    answer = i - offset; 
                    offset = 0; 
                    i = answer;
                } 
                else 
                { 
                    // In the new match, some character is found which is higher 
                    // than the character at same offset in the previous answer.
                    // So new answer cannot be the lexicographical minimum, discard it.
                    offset = 0; 
                }
    

      

  • 相关阅读:
    奶牛碑文
    快速幂算法——人见人爱A^B
    杨辉三角
    iis404 没有设置mime的后缀
    jquery的click和js的funcition中的参数不一样
    asp:timer的权限与操作注意
    .net 文件上传,只上传修改的东西
    vscode的配置 和xdebug配制
    emoji编码后存储
    php 服务器请求其它网页的方法
  • 原文地址:https://www.cnblogs.com/apanda009/p/7701812.html
Copyright © 2011-2022 走看看