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; 
                }
    

      

  • 相关阅读:
    数据切分——Atlas介绍
    HDU 5015 233Matrix (构造矩阵)
    Wincc操作数据库SQLSERVER
    UIWebView 设置背景为透明
    29个你必须知道的Linux命令
    【读书笔记】iOS-UIWindow-WindowLevel
    linux下uart应用编程
    Java Web HelloWorld!
    手把手图文教你eclipse下如何配置tomcat
    Tomcat安装及配置教程
  • 原文地址:https://www.cnblogs.com/apanda009/p/7701812.html
Copyright © 2011-2022 走看看