求教 557. Reverse Words in a String III,使用 C 语言写..

2017-06-20 19:23:14 +08:00
 nomemo

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;
}
2852 次点击
所在节点    程序员
9 条回复
bombless
2017-06-20 20:12:35 +08:00
是字面量对应的匿名数组不可写而已。
其实是一个运行时行为,和常量什么的就没啥关系了
Mirana
2017-06-20 20:21:03 +08:00
传进来的不是常量啊
mason961125
2017-06-20 20:30:52 +08:00
C 什么时候不许改字符串了?和 Python 搞混了?
skydiver
2017-06-20 20:37:06 +08:00
用异或做交换的直接 pass
mrvon
2017-06-20 20:38:13 +08:00
你仔细看,这个是
char* s
而不是
const char* s
nomemo
2017-06-20 20:48:06 +08:00
@bombless
@Mirana
@mrvon

感谢,明白了


@skydiver

请指教原因?
si
2017-06-21 09:57:26 +08:00
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"拷贝到数组里面。数组是允许读写的。
ryd994
2017-06-21 11:37:17 +08:00
任何\0 结尾的 char[] 都是 C-string
demerol
2017-06-21 13:27:17 +08:00
现在的 gcc 貌似 xor 的速度不如加个 temp

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/369890

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX