zoukankan      html  css  js  c++  java
  • STL: string:erase

    leetcode: permutation sequence

    用了https://github.com/soulmachine/leetcode上面康托编码的思路:

    class Solution {
    public:
        string getPermutation(int n, int k) {
           string s(n,'0');
           for(int i=1;i<=n;i++) {
                s[i-1]+=i;   
           }
           string res = "";
           k = k-1;
           int base = getFatorial(n-1);
           for(int i=1;i<n;i++) {
               int index = k/base;
               k = k%base;
               base/=n-i;
               res+=s[index];
               s.erase(index,1);
           }
           res+=s[0];
           return res;
        }
        
        int getFatorial(int n) {
            int res = 1;
            for(int i=1;i<=n;i++) {
                res*=i;
            }
            return res;
        }
    };

    主要看一下string的erase用法:

    sequence (1)
    string& erase (size_t pos = 0, size_t len = npos);
    
    character (2)
    iterator erase (iterator p);
    
    range (3)
    iterator erase (iterator first, iterator last);

    Erases part of the string, reducing its length:
    (1) sequence

    Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos.
    Notice that the default argument erases all characters in the string (like member function clear).
    returns *this.
    (2) character
    Erases the character pointed by p.
    (3) range
    Erases the sequence of characters in the range [first,last).
    (2)&(3) return an iterator referring to the character that now occupies the position of the first character erased, or string::end if no such character exists.

    所以上面的代码里用的是erase的第1种方式。

    还可以改改,用第二种方式:

    for(int i=1;i<n;i++) {
               auto p = next(s.begin(),k/base);
               k = k%base;
               base/=n-i;
               res+=*p;
               s.erase(p);
           }

     

  • 相关阅读:
    Oracle学习系列7
    oracle 体系结构
    数据库设计三大范式
    Oracle学习系列6
    Oracle学习系列5
    Unity3D for Android 纹理压缩支持
    Unity项目UI图片压缩格式(UGUI)
    [Unity3D]关于U3D贴图格式压缩
    unity 联机调试(android ios)
    UGUI 文字效果实现(ShadowGradientOutline)
  • 原文地址:https://www.cnblogs.com/parapax/p/3637490.html
Copyright © 2011-2022 走看看