p113 旋转字符串(leetcode 796)

一:解题思路

这个题目的本质就是判断AA字符串中是否包含B字符串。如果语言内置的函数中直接内置函数有字符串包含可以直接使用。

len(A)==len(B) && AA.contains(B) (strstr(AA,B))  Time:O(n^2),Space:O(1)

二:完整代码示例 (C++版和Java版)

方法一C++:

class Solution {
public:
    bool rotateString(string A, string B) 
    {
        return A.size() == B.size() && (A+A).find(B)!=string::npos;
    }
};

方法一Java:

class Solution {
        public boolean rotateString(String A, String B)
        {
               return A.length()==B.length() && (A+A).contains(B);
        }
    }

方法二C++:

class Solution {
public:
    bool rotateString(string A, string B) 
    {
        if (A.size() != B.size()) return false;
        string AA = (A+A);
        int n = A.size();
        int nn = 2 * n;
        for (int i = 0; i <= n; i++)
        {
            int k = i;
            int j = 0;
            for (; k < nn && j < n && AA[k] == B[j]; j++, k++);
            if (j == n) return true;
        }

        return false;
    }
};

方法二Java:

class Solution {
        public boolean rotateString(String A, String B)
        {
               if(A.length()!=B.length()) return false;
               String AA=(A+A);
               int n=A.length();
               int nn=n*2;
               for(int i=0;i<=n;i++)
               {
                   int k=i,j=0;
                   for(;j<n && k<2*n && AA.charAt(k)==B.charAt(j);j++,k++);
                   if(j==n) return true;
               }

               return false;
        }
    }

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12682755.html
今日推荐