CF Vitaly and Strings
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
a
c
b
aaa
zzz
kkk
abcdefg
abcdefh
No such string
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
思路:将字符串看成数字,先从左向右找到第一个不相同的,然后把最右边那位加一,如果超出了Z就进位。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <string> 5 #include <algorithm> 6 #include <cctype> 7 #include <queue> 8 #include <map> 9 using namespace std; 10 11 int main(void) 12 { 13 string s; 14 string t; 15 int loc,len,flag; 16 17 cin >> s >> t; 18 if(s == t) 19 puts("No such string"); 20 else 21 { 22 len = s.size(); 23 flag = 0; 24 25 for(int i = 0;i < len;i ++) 26 if(s[i] < t[i]) 27 { 28 loc = i; 29 break; 30 } 31 if(s[loc] + 1 < t[loc]) 32 { 33 s[loc] += 1; 34 flag = 1; 35 } 36 else 37 { 38 int box = 1; 39 int add = 0; 40 for(int i = len - 1;i > loc;i --) 41 { 42 flag = 1; 43 s[i] += box + add; 44 if(s[i] > 'z') 45 { 46 s[i] = 'a'; 47 add = 1; 48 box = 0; 49 } 50 else 51 { 52 add = 0; 53 box = 0; 54 } 55 } 56 s[loc] += add; 57 if(s == t) 58 { 59 puts("No such string"); 60 return 0; 61 } 62 } 63 if(flag) 64 cout << s << endl; 65 else 66 puts("No such string"); 67 } 68 69 return 0; 70 }