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

  

posted @ 2017-10-20 21:48  apanda009  阅读(94)  评论(0编辑  收藏  举报