您的位置:首页 > 编程语言

在线编程题

2016-03-03 17:03 309 查看
1.对于一个字符串,和字符串中的某一位置,请设计一个算法,将包括i位置在内的左侧部分移动到右边,将右侧部分移动到左边。

给定字符串A和它的长度n以及特定位置p,请返回旋转后的结果。

测试样例:
"ABCDEFGH",8,4

返回:"FGHABCDE"

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
void
rotate(
char
*s1,
int
n,
int
p)

{

for
(
int
i = 0; i < n; i++)

{

s1[i + n] = s1[i];

}

s1[n + n] =
'\0'
;

for
(
int
i = p+1; i < p + n+1; i++)

printf
(
"%c"
, s1[i]);

printf
(
"\n"
);

}


class
StringRotation {

public
:

string rotateString(string A,
int
n,
int
p) {

string B = A + A;

return
B.substr(p+1, n);

}

};


2.

有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。

给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于300。

测试样例:
[[1,2,3],

[4,5,6],

[7,8,9]],3

返回:[[7,4,1],

  [8,5,2],

  [9,6,3]]

12345678910111213141516171819[code]class
Rotate {
public
:
vector<vector<
int
> > rotateMatrix(vector<vector<
int
> > mat,
int
n){
// write code here
vector<
int
> v1;
vector<vector<
int
>> v_ret;
for
(
int
i = 0; i < n; i++)
{
v1.clear();
for
(
int
j = 0; j < n; j++)
{
v1.push_back(mat[n - 1 - j][i]);
}
v_ret.push_back(v1);
}
return
v_ret;
}
};
[/code]
3.请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展 开。此时有1条折痕,突起的⽅向指向纸条的背⾯,这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。给定折的次数n,请返回从上到下的折痕的数组,若为下折痕则对应元素为"down",若为上折痕则为"up".测试样例:3
返回:["down","down","up","down","down","up","up"]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
class
FoldPaper

{

public
:

vector<string> foldPaper(
int
n)

{

// write code here

vector<string> v;

pushs(v, n,
"down"
);

return
v;

}

void
pushs(vector<string> &v,
int
n,string s)

{

if
(n > 0)

{

pushs(v, n - 1,
"down"
);

v.push_back(s);

pushs(v, n - 1,
"up"
);

}

}

};


提示:折痕其实是二叉树结构。该二叉树的特点是:根节点是下,每一个节点的左节点是下,右节点是上。该二叉树的中序遍历即为答案,但不需要构造一颗二叉树,用递归方法可打印出来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: