diff options
author | Jack Sangdahl <[email protected]> | 2024-11-02 19:28:52 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-11-02 19:28:52 -0600 |
commit | 20fb571e363b19bec8d6f595d471de8fdb01a95b (patch) | |
tree | e0d0f8261c0fcbebc9ff06bdae02bc52690f0b85 | |
parent | 4c3377364808ac2fe55a070a0a2adf448280090f (diff) | |
download | leetcode-20fb571e363b19bec8d6f595d471de8fdb01a95b.tar.gz leetcode-20fb571e363b19bec8d6f595d471de8fdb01a95b.zip |
796. rotate string
-rw-r--r-- | rotate_string.c | 31 | ||||
-rw-r--r-- | rotate_string.py | 24 |
2 files changed, 55 insertions, 0 deletions
diff --git a/rotate_string.c b/rotate_string.c new file mode 100644 index 0000000..cb38ca6 --- /dev/null +++ b/rotate_string.c @@ -0,0 +1,31 @@ +// 796. Rotate String +#include "leetcode.h" + +/* + * given two strings 's' and 'goal', return 'true' if and only if 's' can become + * 'goal' after some number of shifts on 's'. a shift on 's' consists of moving + * the leftmost character of 's' to the rightmost position. for example, if 's = + * "abcde"', then it will be "bcdea" after one shift. + */ + +bool rotateString(char *s, char *goal) { + int sn = strlen(s), gn = strlen(goal); + if (sn == gn) { + for (int i = 0; i < sn; i++) { + if (!strcmp(s, goal)) + return true; + char tmp = s[0]; + for (int j = 0; j < gn - 1; j++) + s[j] = s[j + 1]; + s[sn - 1] = tmp; + } + } + return false; +} + +int main() { + char *s1 = "abcde", *g1 = "cdeab"; + char *s2 = "abcde", *g2 = "abced"; + printf("%d\n", rotateString(s1, g1)); // expect: 1 + printf("%d\n", rotateString(s2, g2)); // expect: 0 +} diff --git a/rotate_string.py b/rotate_string.py new file mode 100644 index 0000000..ee47c41 --- /dev/null +++ b/rotate_string.py @@ -0,0 +1,24 @@ +# 796. Rotate String + +""" +given two strings 's' and 'goal', return 'true' if and only if 's' can become +'goal' after some number of shifts on 's'. a shift on 's' consists of moving +the leftmost character of 's' to the rightmost position. for example, if 's = +"abcde"', then it will be "bcdea" after one shift. +""" + + +class Solution(object): + def rotateString(self, s, goal): + """ + :type s: str + :type goal: str + :rtype: bool + """ + return len(s) == len(goal) and goal in s + s + + +if __name__ == "__main__": + obj = Solution() + print(obj.rotateString(s="abcde", goal="cdeab")) + print(obj.rotateString(s="abcde", goal="abced")) |