码迷,mamicode.com
首页 > 系统相关 > 详细

精简Linux文件路径

时间:2014-07-22 23:01:32      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:blog   os   文件   io   2014   re   

精简Linux的文件路径:

  1. ..回退的功能
  2. .留在当前目录
  3. //只保留一个/
  4. abc/..要返回.
  5. 报错
  6. 删除最后一个/
主要思路: 用栈记录路径的起始位置,讨论/后的不同情况即可:

#include <iostream>
#include <map>
#include <algorithm>
#include <limits.h>
#include <assert.h>
#include <stack>
using namespace std;
int selectK(int num[], int k, int l, int r) {
  
  assert(k <= (r - l + 1) && k >= 1);
  int mid = (l + r) / 2, i = l, j = r;
  while (i <= j) {
    while (num[i] < num[mid]) {
      ++i;
    }
    while (num[j] > num[mid]) {
      --j;
    }
    if (i <= j) {
      swap(num[i],num[j]);
      ++i,--j;
    }
  }
  if (k == i - l)
    return num[i - 1];
  else if (k < i - l)
    return selectK(num, k, l, i -1);
  else if (k == j + 1 - l)
    return num[j + 1];
  else
    return selectK(num, k - (j - l + 2), j + 2, r);
}
void pathcompress(char* str) {
  int i = 0, j = 0;

  char prev = ‘\0‘;
  stack<int> offset;
  offset.push(0);
  while(str[i]) {
    if (prev == ‘/‘) {
        if (str[i] == ‘.‘ && (str[i + 1] == ‘/‘ || str[i + 1] == ‘\0‘)) {
          prev = str[i + 1], i += 1;
        }
        else if (str[i] == ‘.‘ && str[i + 1] == ‘.‘ && (str[i + 2] == ‘/‘ || str[i + 2] == ‘\0‘)) {
          i += 2;
          if (offset.empty()) {
            cout << "error" << endl;
            return;            
          }
          j = offset.top();
          offset.pop();
          if (offset.empty() && str[0] == ‘/‘) {
            cout << "error" << endl;
            return;
          }
        }
        else if (str[i] == ‘/‘) {
          prev = str[i++];
        }
        else {
          offset.push(j);
          prev = str[i];
          str[j++] = str[i++];        
        }
    }
    else {
      prev = str[i];
      str[j++] = str[i++];
    }
  }
  if (j >=3 && str[j - 1] == ‘/‘ && str[j-2] == ‘/‘)
    str[j-2] = ‘\0‘;
  else if (j >= 2 && str[j - 1] == ‘/‘)
    str[j-1] = ‘\0‘;
  else
    str[j] = ‘\0‘;
  if (str[0] == ‘\0‘){
    str[0] = ‘.‘;
    str[1] = ‘\0‘;
  }
    
}


int main()
{
  int num[] = {3,2,1,4,5};
  int res1 = selectK(num, 1, 0, 4);
  int res2 = selectK(num, 2, 0, 4);
  int res3 = selectK(num, 3, 0, 4);
  int res4 = selectK(num, 4, 0, 4);
  int res5 = selectK(num, 5, 0, 4);
 // int res6 = selectK(num, 6, 0, 4);

  //char str[] = "////";
  char str[] = "/.abc/xxx./abc/bacd/.././bcd/fsgs/../../../x/y/z/../../../..";
  pathcompress(str);
  printf("%s\n",str);

  return 0;
}


精简Linux文件路径,码迷,mamicode.com

精简Linux文件路径

标签:blog   os   文件   io   2014   re   

原文地址:http://blog.csdn.net/taoqick/article/details/24829317

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!