C# Walkthrough 80%


  • 0
    M

    We know that the string must be built by an inner string. Note that we don't have to try all permutations of a string at every size of inner string because the inner string must represent the rest of the string, too.

    public class Solution {
        public bool RepeatedSubstringPattern(string s) {
            StringBuilder sb = new StringBuilder();
            for (int i = s.Length / 2; i >= 1; i--) {
                if (s.Length % i == 0) {
                    string inner = s.Substring(0, i);
                    sb.Clear();
                    for (int j = 0; j < (s.Length / i); j++) {
                        sb.Append(inner);
                    }
                    if (sb.ToString().Equals(s)) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
    
    • Loop from half the string size to one. This will represent inner string size.
    • Check if the string size is divisible by the loop counter size. If not, move on and decrement the counter.
    • Otherwise, take the first substring of s of the counter size. Append it to itself (via StringBuilder to save time) the divisibility amount.
    • Check equality now. If not equal, move on and decrement the counter. But if a match is found, we should return true.
    • Return false if all possibilities are tried.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.