一道很經典的字符串算法題:
把一個字符串的大寫字母放到字符串的後面,各個字符的相對位置不變,且不能申請額外的空間。
例如
AkleBiCeilD, 調整後應該是 kleieilABCD
第一次做的時候寫的是類似冒泡的兩兩交換,時間複雜度是O(n*n),明顯當n達到萬級的時候就會TLE,是很笨的方法。而且聲明瞭 char t;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
string s;
while(cin>>s)
{
int len = s.length();
int pos = len-1;
for(int i=len-1;i>=0;--i){
if(s[i]>='a' && s[i]<='z'){//找最後一個小寫字母的位置
pos = i;
break;
}
}
for(int i = len-1;i>0;--i){
if(s[i]>='a' && s[i]<='z' && s[i-1]>='A' && s[i-1]<='Z')
{ //出現了類似 Aa 這種大寫字母在前面的情況
char t;
for(int j=i-1;j<pos;++j)
{ //i-1到pos 位置循環兩兩交換,把大寫字母放到後面
t = s[j];
s[j]=s[j+1];
s[j+1]=t;
}
pos--; //pos位置前移,後面是移好的大寫字母
}
}
cout<<s<<endl;
}
return 0;
}
(事實上,如果你要交換兩個值,而不用到第三個值的時候,你可以這樣寫
a^=b;
b^=a;
a^=b;
利用的原理是
是一個整數與另外一個數進行兩次異或運算仍然是其本身,而且與0異或也是其本身
基本原理用式子表達如下:右邊數字表示狀態
(1) A ^ A = 0;
(2) A1 = A0 ^B0;
(3) B1 = A1 ^B0 = (A0 ^ B0) ^ B0 = A0 ^ (B0 ^ B0) = A0 ^ 0 = A0;
(4) A2 = A1 ^ B1 = B1 ^ A1 = A0 ^ (A0 ^B0) = 0^B0=B0;
)
實際上,若果只是oj測評,不想Leetcode那樣需要返回數組檢查,直接輸出2次就可以了,很強的方法。。。
#include <iostream>
#include <string.h>
using namespace std;
int main(){
string s;
while(cin >> s){
for(int i = 0; i < s.length(); i++)
if(s[i] >= 'a' && s[i] <= 'z')
cout << s[i];
for(int i = 0; i < s.length(); i++)
if(s[i] <= 'Z' && s[i] >= 'A')
cout << s[i];
cout << endl;
}
return 0;
}
再耍流氓一點,調用STL 的 stable_partition 也是可以的。但是筆試就不行
#include <iostream>
#include <algorithm>
using namespace std;
bool isLower(char c) {
return c>='a';
}
int main() {
string s;
while(cin >> s) {
stable_partition(s.begin(),s.end(),isLower);
cout << s << endl;
}
}
既然說到了stable_partition,順便說一下和 partition 的區別
bool Fun(char c)
{
return c=='*';
}
int main()
{
string str = "***b**a**c**d**";
string str1(str);
string str2(str);
std::partition(std::begin(str1), std::end(str1),Fun);
std::stable_partition(std::begin(str2), std::end(str2),Fun);
cout<<"str1="<<str1.c_str()<<endl;
cout<<"str2="<<str2.c_str()<<endl;
return 0;
}
運行結構是
str1=***********cdab
str2=***********bacd
從運行結果上看,partition函數把所有的都提前了,但是其他字母的順序是打亂的,而stable_partition函數除了把號提前,其他字母的順序和原來是一樣的
Fun函數判斷傳入的char是不是*,如果是,就返回true
stable_partition 函數,前兩個參數規定了排序的範圍,最後一個參數要傳入一個函數名,程序會遍歷規定範圍內的元素並傳入Fun函數,根據返回值決定這個元素是往前放還是往後放