-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathReverseSentence.cs
More file actions
122 lines (108 loc) · 3.69 KB
/
Copy pathReverseSentence.cs
File metadata and controls
122 lines (108 loc) · 3.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
题目名称:
翻转单词顺序列
题目描述:
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。
例如,“student. a am I”。
后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。
Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
代码结构:
class Solution
{
public string ReverseSentence(string str)
{
// write code here
}
}
*/
using System;
namespace ReverseSentence {
class Solution {
/// <summary>
/// 解法1
/// 基本思路:
/// 利用Split函数将字符串根据" "拆分成多个子字符串,翻转子字符串的顺序,然后再用Join函数通过" "连接起来
/// </summary>
public void Reverse(string[] array, int m, int n){
for(int i = m, j = n; i < j; i++, j--){
string temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public string ReverseSentence(string str)
{
if (str == null){
return null;
}
string[] strs = str.Split(" ");
Reverse(strs, 0, strs.Length - 1);
return string.Join(" ", strs);
}
/// <summary>
/// 解法2
/// 基本思路:
/// 一个一个字符处理,用tmp保存' '之前的字符串,遇到' '之后,将tmp添加到结果的前面
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string ReverseSentence2(string str)
{
if (str == null){
return null;
}
string ret = "", tmp = "";
for(int i = 0; i < str.Length; i ++){
if(str[i] == ' '){
ret = ' ' + tmp + ret;
tmp = "";
}else{
tmp += str[i];
}
}
ret = tmp + ret;
return ret;
}
/// <summary>
/// 解法3
/// 基本思路:
/// 先遍历字符数组找到每个单词,然后对每个单词进行翻转
/// 最后再整体将整个字符数组进行翻转
/// </summary>
public string ReverseSentence3(string str)
{
if(str == null || str.Length == 0) return str;
char[] array = str.ToCharArray();
int i = 0, j = 0;
while(i < array.Length){
if(array[i] == ' '){
Reverse(array, j, i - 1);
j = i + 1;
}
i ++;
}
Reverse(array, j, i - 1);
Reverse(array, 0, array.Length - 1);
return new string(array);
}
public void Reverse(char[] array, int i, int j){
while(i < j){
char temp = array[i];
array[i ++] = array[j];
array[j --] = temp;
}
}
public void Test() {
string str = "student. a am I";
// str = "";
// str = "am I";
// str = "am ";
// str = null;
str = "student. a am I";
// Console.WriteLine(ReverseSentence(str));
// Console.WriteLine(ReverseSentence2(str));
Console.WriteLine(ReverseSentence3(str));
}
}
}