Swift, need to convert String->NSString->String

  • 0

    The idea is from @Xianming.Chen, https://discuss.leetcode.com/topic/79495/my-one-line-c-solution in C++, and thank you so much for your great solution!
    I try to write it in Swift, and it is a little annoying because that in Swift, the

    • String (which is struct) does not have API .substring(from:), which returns String, and
    • NSString (which is class) does not have API .contains(string), will also returns String.
      I think it should be a better way to do this in Swift.
    class Solution {
        func repeatedSubstringPattern(_ s: String) -> Bool {
        // s+s must contains pattern if s contains either;
            let ns = NSString(string: s+s)
            let nssb = NSString(string: ns.substring(from: 1)) // NSString
            let str = nssb.substring(to: s.characters.count * 2 - 2) // String
            return str.contains(s) // String

  • 0

    You are so welcome! We just learn from each other, and sharing keeps us moving ahead!

Log in to reply

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