问题
给定一个只包含大小写字母和空格的字符串,在线性时间内对它做一些变形.把这个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。比如"Hello World",变形后成了"wORLD hELLO"。
输入描述给定一个字符串以及他的长度n(1<=n<=500)。题目保证字符串有大小写字母和空格构成。输出描述返回变形后的字符串。输入例子"This is a sample",16输出例子"SAMPLE A IS tHIS"以下是我的源代码:
OS:win10IDE:visual studio 2010第一种思路:用字符串集合分别存储单词,然后合并。
string ReverseWords(string s, int n) { string *t=new string[100]; string s1; int num=0;//the word cursor of s int i=0;//the char cursor of s //Cut s into words and put the words in the array t while(1){ int j=0;//length of the word //Forward with the char cursor of s and cut when comes space //Get out a word of s while(s.at(i)!=32){ i++; j++; //stop when comes the end of s if(i>=n) break; } //put the word of in t t[num].assign(s,i-j,j); num++; //stop when comes the end of s if(i>=n) break; i++; } int k=0;//the char cursor of s //traverse the words of s from right to left for(int i=0;i64&&s1.at(k)<91){ s1.at(k)=s1.at(k)+32; } else if(s1.at(k)>96&&s1.at(k)<123){ s1.at(k)=s1.at(k)-32; } k++; } if(k
第二种思路:动态地将单词插入目标字符串头部
string ReverseWords(string s, int n) { string s1; int num=0;//the word cursor of s int i=0;//the char cursor of s while(1){ int j=0;//length of the word //Forward with the char cursor of s and cut when comes space //Get out a word of s while(s.at(i)!=32){ i++; j++; //stop when comes the end of s if(i>=n) break; } string r; r.assign(s,i-j,j);//r is the word s1.insert(0,r);//insert r in the beginning of s1 num++; if(i64&&int(s1.at(i)<91)){ s1.at(i)=s1.at(i)+32; } else if(s1.at(i)>96&&s1.at(i)<123){//不能写成if s1.at(i)=s1.at(i)-32; } } return s1;}
注意事项
1.string对象在未初始化前,不能按位置给相应的字符赋值。否则将访问未知地址,导致程序意外停止。
2.string的接口功能强大,要灵活应用。比如方法二中用到的insert(),在方法一的基础上大大简化编程复杂度,使得代码更加简洁。其实所有C++中的STL接口不都是这样吗?如果恰当运用将事半功倍。
3.对于用new初始化的指针,千万记得要加[],给定必要的空间大小。如string *t=new string[100];
否则,t[1];
就是访问未知内存的错误!
`string *t=new string[100];`:申请一个指针t,指向一个字符串数组。`string *t=new string;`:申请一个指针t,指向一个字符串。