GVKun编程网logo

你如何使用 String.substringWithRange?(或者,范围如何在 Swift 中工作?)(string语句怎么用)

11

在本文中,我们将为您详细介绍你如何使用String.substringWithRange?的相关知识,并且为您解答关于或者,范围如何在Swift中工作?的疑问,此外,我们还会提供一些关于003_Lon

在本文中,我们将为您详细介绍你如何使用 String.substringWithRange?的相关知识,并且为您解答关于或者,范围如何在 Swift 中工作?的疑问,此外,我们还会提供一些关于003_LongestSubstringWithoutRepeatingCharacters、3. Longest Substring Without Repeating Characters、ios – 在Swift中枚举SubstringsInRange、ios – 带有substringWithRange的Swift 2.0字符串的有用信息。

本文目录一览:

你如何使用 String.substringWithRange?(或者,范围如何在 Swift 中工作?)(string语句怎么用)

你如何使用 String.substringWithRange?(或者,范围如何在 Swift 中工作?)(string语句怎么用)

我还没有弄清楚如何String在 Swift 中获取 a 的子字符串:

var str = 鈥淗ello,playground鈥�
func test(str: String) -> String {
 return str.substringWithRange( /* What goes here? */ )
}
test (str)

我无法在 Swift 中创建 Range。Playground 中的自动完成功能非常有用 - 这就是它的建议:

return str.substringWithRange(aRange: Range<String.Index>)

我在 Swift 标准参考库中没有找到任何有用的东西。这是另一个疯狂的猜测:

return str.substringWithRange(Range(0,1))

还有这个:

let r:Range<String.Index> = Range<String.Index>(start: 0,end: 2)
return str.substringWithRange(r)

我已经看到了其他答案(Finding index of character in Swift
String
)似乎表明,因为String它是一个桥类型NSString,所以“旧”方法应该可以工作,但不清楚如何 -
例如,这也不起作用(似乎不是有效的语法):

let x = str.substringWithRange(NSMakeRange(0,3))

想法?

003_LongestSubstringWithoutRepeatingCharacters

003_LongestSubstringWithoutRepeatingCharacters

/***
 *
 * Given a string, find the length of the longest substring without repeating characters.
 *
 * Example 1:
 *
 * Input: "abcabcbb"
 * Output: 3
 * Explanation: The answer is "abc", with the length of 3.
 * Example 2:
 *
 * Input: "bbbbb"
 * Output: 1
 * Explanation: The answer is "b", with the length of 1.
 * Example 3:
 *
 * Input: "pwwkew"
 * Output: 3
 * Explanation: The answer is "wke", with the length of 3.
 *              Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 *
 *
 */
/***
* 关键:
* 先遍历一遍放进hashmap,因此复杂度是O(n)
*
*/
public class N003_LongestSubstringWithoutRepeatingCharacters {
        /***
     * 使用HashMap记录字符上次出现的位置
     * 用pre记录最近重复字符出现的位置
     * 则i(当前位置)-pre就是当前字符最长无重复字符的长度
     * 取最大的就是字符串的最长无重复字符的长度
     *
     * 时间复杂度:O(n)
     */
    public static int lengthOfLongestSubstring(String str) {
        if (str == null || str.length() < 1)
            return 0;

        // 记录字符上次出现的位置
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        // 最近出现重复字符的位置
        int pre = -1;

        for (int i = 0, strLen = str.length(); i < strLen; i++) {
            Character ch = str.charAt(i);
            Integer index = map.get(ch);
            if (index != null)
                pre = Math.max(pre, index);     //这一步很关键,取前一个相同字符位置,而不是后一个;后一个字符还有可能成为字串的元素
            max = Math.max(max, i - pre);
            map.put(ch, i);
        }

        return max;
    }

    public static void main(String args[]) {
        String input = "nevereverbeacoder";

        int len = lengthOfLongestSubstring(input);
        System.out.println(len);

    }
}

 

3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

问题描述:

Given a string, find the length of the longest substringwithout repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

解题思路:

这道题我首先想到的是使用 set 来确保 char 唯一,使用 queue 来进行字符串的遍历。

当遇见未出现的字符时加入 set 和 queue。

若遇见出现的字符则弹出队首元素并且删除 set 中的元素直至不出现重复。

时间复杂度为 O (n): 数组中的每个元素只进入 set 和 queue 一次(如果考虑到 set 和 queue 的增删操作可能还要乘个啥)。

空间复杂度为 O (n)

 

看了一下最优解,发现别人充分利用字符可以被穷举这一特性进行解答,可以达到时间复杂度 O (n), 空间复杂度 O (1)。

 

代码:

我的方法:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //store current unrepeated char
        queue<char> char_q;
        //store current chars
        set<char> char_set;
        int ret = 0;
        for(char c : s){
            if(char_set.count(c) != 0){
                ret = max((int)char_q.size(), ret);
                while(char_q.front() != c){
                    char_set.erase(char_q.front());
                    char_q.pop();
                }
                char_set.erase(char_q.front());
                char_q.pop();
            }
            char_q.push(c);
            char_set.insert(c);
        }
        ret = max((int)char_q.size(), ret);
        return ret;
    }
};

 

最优解法:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
    }
};

 

ios – 在Swift中枚举SubstringsInRange

ios – 在Swift中枚举SubstringsInRange

我将现有的目标c代码(ios)重写为 Swift,面对enumerateSubstringsInRange方法的一些问题.任何人都可以帮我将下面的代码转换为Swift吗?

[contentString enumerateSubstringsInRange:NSMakeRange(0,[contentString length])
                               options:NsstringEnumerationByComposedCharacterSequences
                               usingBlock: ^(Nsstring *substring,NSRange substringRange,NSRange enclosingRange,BOOL *stop) {

          if(substring.length >= 2) {
              /* my code goes here */
          }
    }
]

解决方法

试试这个:

contentString.enumerateSubstringsInRange(NSMakeRange(0,(contentString as Nsstring).length),options: NsstringEnumerationoptions.ByComposedCharacterSequences) { (substring,substringRange,enclosingRange,stop) -> () in
    if((substring as Nsstring).length >= 2) {
        NSLog("%@",substring)
    } 
}

请注意,为了访问String的length属性,您必须将其强制转换为Nsstring,如上所示.

ios – 带有substringWithRange的Swift 2.0字符串

ios – 带有substringWithRange的Swift 2.0字符串

我想从String中获取第一个char.它应该很容易,但我不能在 Swift 2.0中使用(使用Xcode beta 6).

Get nth character of a string in Swift programming language

我也试过那种方法.它使用扩展但我无法使用该方法检索.我可以知道怎么办?

解决方法

没有强制转换为Nsstring的两种解决方案
let string = "Hello"
let firstChar1 = string.substringToIndex(string.startIndex.successor())

let firstChar2 = string.characters.first

Swift 2更新:

由于Swift 2返回Character而不是String,因此必须创建一个新的String.

let firstChar2 = String(string.characters.first!)

Swift 3的更新:

successor()已被index替换(after:..)

let firstChar1 = string.substring(to:string.index(after: string.startIndex))

关于你如何使用 String.substringWithRange?或者,范围如何在 Swift 中工作?的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于003_LongestSubstringWithoutRepeatingCharacters、3. Longest Substring Without Repeating Characters、ios – 在Swift中枚举SubstringsInRange、ios – 带有substringWithRange的Swift 2.0字符串等相关内容,可以在本站寻找。

本文标签: