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

      

  • 相关阅读:
    C++学习9 this指针详解
    福建省第八届 Triangles
    UVA 11584 Partitioning by Palindromes
    POJ 2752 Seek the Name, Seek the Fame
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    HDU 2988 Dark roads(kruskal模板题)
    HDU 1385 Minimum Transport Cost
    HDU 2112 HDU Today
    HDU 1548 A strange lift(最短路&&bfs)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7701812.html
Copyright © 2011-2022 走看看