Swift, C++ : take string as an array of characters


  • 0
    X
    //Swift
    class Solution {
        func reverseStr(_ s: String, _ k: Int) -> String {
            var chars = Array(s.characters) // turn string into array for easy swap
            let sz = chars.count
            if k < 2 { return s }
            var head = 0, tail = k-1
            while head < tail && tail < sz + k {
                reverse(&chars, head, tail)
                head += 2 * k
                tail += 2 * k
            }
            return String(chars) // turn chars back to string
        }
        private func reverse(_ chars:inout [Character], _ head: Int, _ tail: Int) {
            var h = head
            var t = tail < chars.count ? tail : chars.count-1
            var tmp : Character?
            while h < t {
                tmp = chars[h]
                chars[h] = chars[t]
                chars[t] = tmp!
                h += 1
                t -= 1
            }
        }
    }
    
    // C++
    class Solution {
    public:
        string reverseStr(string s, int k) {
            if(k < 2) return s; 
            int head = 0, tail = k-1, sz = s.size(); 
            while(head < sz && tail < sz+k) {
                reverse(head, tail, s); 
                head += (2 * k); 
                tail += (2 * k); 
            }
            return s; 
        }
        void reverse(int head, int tail, string &s){
            // cout<<head<<","<<tail<<endl;
            if(head >= s.size()) return; 
            tail = (tail < s.size()) ? tail : s.size()-1; 
            char tmp;
            while(head < tail){
                tmp = s[head]; 
                s[head] = s[tail]; 
                s[tail] = tmp; 
                head += 1; 
                tail -= 1; 
            }
        }
    };
    

Log in to reply
 

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