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

      

  • 相关阅读:
    JavaScript DOM 编程艺术 公用方法
    JavaScript DOM 编程艺术
    Echart 的formatter及重写line chart
    PHP 导出csv
    Linux 搭建PHP环境
    学习新思路
    fork产生子进程利用pipe管道通信
    进程间通信 管道
    进程间通信(IPC) 简介
    java 多态
  • 原文地址:https://www.cnblogs.com/apanda009/p/7701812.html
Copyright © 2011-2022 走看看