使用C/C++语言写一个函数,实现字符串的反转,要求不能用任何系统函数,且时间复杂度最小。
函数原型是:char *reverse_str(char *str)
#include <iostream> #include <stack> char *reverse_str(char *str){ if (str==NULL) { return str; } int lens = 0; std::stack<char> stk; while (*str != '\0'){ stk.push(*str); ++lens; ++str; } char *dest_org = (char*)malloc(lens + 1); char *dest = dest_org; #if 1 for (size_t i = 0; i < lens; i++) { *dest = stk.top(); stk.pop(); ++dest; } #else while (!stk.empty()){ *dest = stk.top(); stk.pop(); ++dest; } #endif *dest = '\0'; return dest_org; } int main(){ char str[] = "1234567"; char *dest = reverse_str(str); printf("%s\n", dest); system("pause"); return 0; }
public class Main { public static void main(String[] args) { String str = "abc"; System.out.println(reverse(str)); } public static String reverse(String str) { char[] seq = str.toCharArray(); int pre = 0; int end = str.length() - 1; while (pre != end) { char temp = seq[pre]; seq[pre] = seq[end]; seq[end] = temp; pre++; end--; } return new String(seq); } }
// 字符串的反转 O(n) char *reverse_str(char *str) { if(NULL == str || '\0' == *str) { return str; } char *end = str; char *start = str; // 头指针 while (*end != '\0') { end++; } // 尾指针 --end; while (start < end) { char temp = *start; *start = *end; *end = temp; start++; end--; } return str; }
char *reverse_str(char *str) { if (!str || str[0] == '\0') { return str; } // find the tail int j; for (j = 0; str[j + 1] != '\0'; j++); int middle = j / 2 + j % 2; for (int i = 0; i < middle; i++, j--) { char tmp = str[i]; str[i] = str[j]; str[j] = tmp; } return str; }