通过绝对路径计算相对路径||Young氏矩阵

某公司笔试的两道题~


同学发来了某公司的笔试题,就拿来做做: 第一题: 已知两文件的路径,例如a文件的路径为‘/qihoo/app/a/b/c/d/new.c’ b文件的路径为 /qihoo/app/1/2/test.c;求b相对于a的相对路径: 分析:首先要理解绝对路径与相对路径的概念,刚开始做的时候理解错了其意思,导致做错了…… - -|| * 相对路径:从当前路径开始的路径 * 绝对路径:从盘符开始的路径,也就是从根文件下开始的路径 * ../ 表示向上一级

依据此概念可知在a文件下要访问到b节点,那么应当向上返回4次,然后在向下寻找子目录

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 string& findab(const string& a, string &b)
 5 {
 6  if(a.empty()||b.empty())
 7      return b;
 8  int flag[2];
 9  int count =0;
10  string temp1;
11  bool flag0=1;
12  int lengths=0;
13  for(int i=0;i<a.length();++i)
14  {
15  
16      if(count==2)
17      {
18          count=0;
19          string c=a.substr(flag[0]+1,flag[1]-1-flag[0]);
20          string d=b.substr(flag[0]+1,flag[1]-1-flag[0]);
21          if(flag0&&c==d)
22          {
23              lengths+=(flag[1]-flag[0]);
24              i--;
25              
26          }
27          else
28          {    
29              i--;
30              flag0=0;
31              temp1.append("../");
32          }
33          
34              
35      }
36      if(a[i]=='/')
37      {
38          flag[count]=i;
39          count++;
40 
41      }
42  }
43  b.erase(0,lengths+1);
44  b.insert(0,temp1);
45  return b;
46 }

采用了一个标志数组,提取两个/之间的单词比较,先找到第一个不同的地方记录其长度(相同的父目录)然后向下记录要回溯的文件夹数量,最后将字符串拼接即可 程序比较简单,又重温了一下string里的操作~ 第二题比较水,经典的Young氏矩阵:

 1 using namespace std;    
 2 struct Coord{
 3  int x,y;
 4 };  
 5 template<int row,int col>
 6 Coord findkey(float(&mat)[row][col],const float &key)
 7 {
 8  Coord ans;
 9  ans.x=row;ans.y=col;
10  if(key<mat[row-1][col-1]||key>mat[0][0])
11  {
12      cout<<"No answer"<<endl;
13      return Coord;
14  }
15  int i=0,j=col-1;
16  while(i<=row&&j>=0)
17  {
18      if(key==mat[i][j]) break;
19      else if(key>mat[i][j])
20          --j;
21      else
22          ++i;
23  }
24  ans.x=i;
25  ans.y=j;
26  return ans;
27 }

题目要求返回一个坐标……这里有个疑问就是当为空时我应该返回什么……



Previous     Next
SureD /
Published under (CC) BY-NC-SA in categories 算法  tagged with 算法 
分享到: 更多
>