so basically we have a string s , and if its possible to rotate it and get to the string goal then we can return true , if it is not possible then we return false
Lets just see 1 example
Input: s = "abcde", goal = "cdeab"
Output: true
Here the s string after 1 rotation becomes "bcdea" ,
after one more rotation it become "cdeab"
so we r able to get to the goal ie "cdeab" on rotations so the output is true
Now the approach is we go through all the rotations ie its length times and see if at any time matches with goal , if it matches then we return true .
Now the question is how to rotate a string
simple -> if s is string then s.substring(1) removes the first character , example s="abc" then s.substring(1) becomes "bc" , now we want that removed character to be at last so
we code
s.substring(1) + s[0];
to rotate string
there are other ways to remove first character of string u can go through this article
now we iterate through its length number of times and see for a match so the code becomes
/**
* @param {string} s
* @param {string} goal
* @return {boolean}
*/
var rotateString = function(s, goal) {
for(let i=0;i<s.length;i++){
s = s.substring(1) + s[0];
if(s === goal){
return true
}
}
return false
};
please let me know if you have any queries 😄 . also try to explore other possible solutions in the leetcode
Top comments (0)