WaTEr 水题,喜欢 srds写的屎山 嵌套两层判断,从第一位往下判断是否奇偶性相同; 然后判断是否第i+1项大于第i项,使用swap函数进行交换 直接返回s就可以得到正确答案了 class Solution { public: string getSmallestString(string s) { int a = s.size(); for (int i = 0; i < a - 1; i++) { if (s[i] % 2 == s[i + 1] % 2) { if (s[i] > s[i + 1]) { swap(s[i], s[i + 1]); break; } } } return s; } };
fluid_heart 喜欢我不会C++吗 char* getSmallestString(char* s) { int len=strlen(s); for(int i=0;i<len-1;++i) { if(s[i]%2==s[i+1]%2&&s[i]>s[i+1]) { char temp=s[i]; s[i]=s[i+1]; s[i+1]=temp; break; } } return s; }
Koarz class Solution { public: string getSmallestString(string s) { for (int i = 1; i < s.size(); i++) { if (s[i] < s[i - 1] && (s[i] & 1) == (s[i - 1] & 1)) { std::swap(s[i], s[i - 1]); break; } } return s; } };
ssssshi 众所周知奇偶互减必为奇,奇奇,偶偶互减必为偶,所以只需要判断(s-s[i+1])%2==0,且本身大于0,然后进行交换 class Solution { public: string getSmallestString(string s) { int l=s.size(); for(int i=0;i<l-1;i++) { if((s[i]-s[i+1])%2==0&&s[i]-s[i+1]>0) { swap(s[i],s[i+1]); break; } } return s; } };
ygxdsh 究极水题,就不写思路了(反正估计也没人看),以后写出难题了再把思路写详细一点吧 class Solution { public: string getSmallestString(string s) { int l=s.size(); for(int i=1;i<l;i++) if(s[i-1]%2==s[i]%2&&s[i]<s[i-1]) { swap(s[i-1],s[i]); break; } return s; } };
xujingyuan C语言:先判断是否满足条件(两个if都要满足),然后进行交换,将字典序大的换到后面,一次操作完成,返回。 char* getSmallestString(char* s) { for(int i=0;s[i+1]!='\0';i++) { if((s[i]%2==0&&s[i+1]%2==0)||(s[i]%2!=0&&s[i+1]%2!=0)) { if(s[i]>s[i+1]) { char ch=s[i]; s[i]=s[i+1]; s[i+1]=ch; break; } } } return s; }
Yln_wlp class Solution { public: string getSmallestString(string s) { int len = s.length(); for(int i = 0;i<len-1;i++){ if(s[i]>s[i+1]&&abs(s[i]-s[i+1])%2==0){ char tmp = s[i]; s[i] = s[i+1]; s[i+1] = tmp; break; } } return s; } };
莉莉白 ♥水一条,第一次就给你了♥ class Solution { public: string getSmallestString(string s) { for(int i = 0; i + 1 < s.size(); ++i){ if(s[i] > s[i + 1] && s[i] % 2 == s[i + 1] %2){ swap(s[i], s[i + 1]); return s; } } return s; } };
wszyh public: string getSmallestString(string s) { int m=s.length(); for(int i=1;i<m;i++){ if(s[i-1]%2==s[i]%2){ if(s[i-1]>s[i]){ swap(s[i-1],s[i]); break; } } } return s; } };```
Mr-Hate 唉,早上看题还想着贪心,晚上写代码就写成枚举所有情况找到最小的了😭 class Solution { public: string getSmallestString(string s) { int n=s.size(); for(int i=0;i<n-1;i++){ int a=(s[i]-'0')%2; int b=(s[i+1]-'0')%2; if(a==b&&s[i]>s[i+1]){ swap(s[i],s[i+1]); return s; } } return s; } };