劍指offer58 翻轉字符串

輸入字符串“the sky is blue”,輸出“blue is sky the”

// python
string = 'the sky is blue'

class Solution(object):
    def reverseWords(self, s):
        s = s.strip()
        res = ""
        i, j = len(s) - 1, len(s)
        while i > 0:
            if s[i] == ' ':
                res += s[i + 1: j] + ' '
                while s[i] == ' ':
                    i -= 1
                j = i + 1
            i -= 1
        return res + s[:j]


s = Solution()
print(s.reverseWords(string))

輸出:

blue is sky the

//OC

NSString *string = @"you! are how";
NSMutableString *endString = [NSMutableString string];
NSInteger subStringLength = 0;
for (NSInteger loc = string.length - 1;  loc >= 0; loc--) {
    NSString *value = [string substringWithRange:NSMakeRange(loc, 1)];
    if ([value isEqualToString:@" "] || loc == 0) {
        if (loc == 0) {
            NSString *subString = [string substringWithRange:NSMakeRange(loc, subStringLength + 1)];
            [endString appendString:subString];
        } else {
            NSString *subString = [string substringWithRange:NSMakeRange(loc + 1, subStringLength)];
            [endString appendString:[NSString stringWithFormat:@"%@%@", subString, @" "]];
        }
        subStringLength = 0;
    } else {
        subStringLength++;
    }
}
NSLog(@"%@", endString);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章