Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
地址: https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description
不使用额外空间,但 c 的字符串不应该是常量不可修改嘛?
为何我看别人写的都是直接对字条串的单个字符进行修改呢
void reverse(int b, int e, char *s){
while(b < e) {
s[b] = s[b] ^ s[e];
s[e] = s[b] ^ s[e];
s[b] = s[b] ^ s[e];
b++;
e--;
}
}
char* reverseWords(char* s) {
int i, s_len = strlen(s), index = 0;
for(i = 0; i <= s_len; i++) {
if((s[i] == ' ') || (s[i] == '\0')){
reverse(index, i - 1, s);
index = i + 1;
}
}
return s;
}
感谢各位
问题解决,我自己写题的时候会使用测试数据
char *testInput = "Let's take LeetCode contest"
虽然是使用C写,但以前就学得不是很精,谢谢指导
1
bombless 2017-06-20 20:12:35 +08:00 via Android 1
是字面量对应的匿名数组不可写而已。
其实是一个运行时行为,和常量什么的就没啥关系了 |
2
Mirana 2017-06-20 20:21:03 +08:00 1
传进来的不是常量啊
|
3
mason961125 2017-06-20 20:30:52 +08:00
C 什么时候不许改字符串了?和 Python 搞混了?
|
4
skydiver 2017-06-20 20:37:06 +08:00 via Android
用异或做交换的直接 pass
|
5
mrvon 2017-06-20 20:38:13 +08:00 1
你仔细看,这个是
char* s 而不是 const char* s |
7
si 2017-06-21 09:57:26 +08:00 1
char *testInput = "Let's take LeetCode contest"; 这种是定义 char 指针,指针指向 "Let's take LeetCode contest",一般编译器会把 "Let's take LeetCode contest" 放到常量段。一般常量段是只读的,如果对它写入,就会崩溃。
char testInput[] = "Let's take LeetCode contest"; 这样是定义一个 char 数组,并把"Let's take LeetCode contest"拷贝到数组里面。数组是允许读写的。 |
8
ryd994 2017-06-21 11:37:17 +08:00
任何\0 结尾的 char[] 都是 C-string
|
9
demerol 2017-06-21 13:27:17 +08:00 via Android 1
现在的 gcc 貌似 xor 的速度不如加个 temp
|