输入字符串“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);