本帖最后由 ios_xiaot 于 2015-7-2 22:38 编辑
- </blockquote></div><div><div class="blockcode"><blockquote>#include <stdio.h>
- #define MAX_BUFFER 100
- int main(int argc, const char * argv[]) {
- // insert code here...
-
- //note:若有相同长度的单词,则全部输出
-
- char buffer[MAX_BUFFER+1] = "warning: this program1 program35 program46 uses gets(), which is unsafe. program2";
- char tmpBuffer[MAX_BUFFER+1] = {0};
- //1.初始化单词最长的起始位置
- int posArray[MAX_BUFFER] = {0};
- //2.拷贝到临时数组中
- strcpy(tmpBuffer,buffer);
-
- //3.定义变量count:字符串最大长度,tmpcount:循环中最大长度,startPos:最长字符串的起始位置
- int i = 0,k = 0,count = 0,tmpcount = 0;
- while (tmpBuffer[i] != '\0') {
- if (' ' == tmpBuffer[i]) {
- //3.1如果最大长度小于,循环中最大长度
- if(count < tmpcount){
- //将pos数组设置为空
- for (int m = 0;m <= k; m++) {
- posArray[m] = 0;
- }
- posArray[0] = i-tmpcount;
- count = tmpcount;
- k = 0;
- }else if(count == tmpcount){
- //3.2如果位置相同,添加新的启示坐标
- posArray[++k] = i-tmpcount;
- }
- tmpcount = 0;
- }
- else{
- tmpcount++;
- }
- i++;
-
- }
-
- //4.检测最后一个单词是否为最长
- if(tmpcount > count){
- //startPos = i - tmpcount;
- for (int m = 0;m <= k; m++) {
- posArray[m] = 0;
- }
- posArray[0] = i - tmpcount;
- k = 0;
- }else if(tmpcount == count){
- posArray[++k] = i-tmpcount;
- }
- //5.循环输出数组
- printf("原的字符串为:%s\n最长的单词为:",buffer);
- for (int m = 0; m <= k; m++) {
- tmpBuffer[posArray[m]+count] = '\0';
- printf("%s ",tmpBuffer+posArray[m]);
- }
- printf("\n");
- return 0;
- }
复制代码
以上是我的解法,当时做题时考虑到有可能有相同长度的单词有可能有重复的,编码时注意到了此点。上面解法感觉有点复杂,请同学们看下是否可以优化下。 另:不知道发此类信息是否违规,若违规则请版主提醒,会及时删除。
|