Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- We will apply BFS.The time complexity allows us to see all the possibility but
- we will also use a map so that we won't repeat
- the same output.
- for every input,If it is present in map,means already visited this string.
- if not in map,compare it with the answer string.
- Now,two modification to do,add a to every odd position and send for bfs.
- second,rotate the string by b and send for bfs.
- */
- unordered_map<string,int> mp;
- string ans;
- void bfs(string s,int a,int b){
- if(mp[s]) return;
- mp[s]=1;
- if(s.compare(ans)<0) ans=s;
- string backup=s;
- for(int i=1;i<s.size();i+=2){
- int temp=s[i]-'0';
- temp+=a;
- temp%=10;
- s[i]=temp+'0';
- }
- bfs(s,a,b);
- s=backup;
- s=s.substr(s.size()-b,b)+s.substr(0,s.size()-b);
- bfs(s,a,b);
- }
- class Solution {
- public:
- string findLexSmallestString(string s, int a, int b) {
- ans=s;
- bfs(s,a,b);
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement