题解 | #字符串变形#

字符串变形

https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e?tpId=295&tqId=44664&ru=%2Fpractice%2F4892d3ff304a4880b7a89ba01f48daf9&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj

毫无状态

class Solution {
public:
    string trans(string s, int n) {
      if (n == 0) {
        return s;
      }
      
      for (int i = 0; i < n; ++i) {
        if (s[i] >= 'A' && s[i] <= 'Z') {
          s[i] = std::tolower(s[i]);
        } else if (s[i] >= 'a' && s[i] <= 'z') {
          s[i] = std::toupper(s[i]);
        } 
      }
      
      std::reverse(s.begin(), s.end());
      
      for (int i = 0; i < n; ++i) {
        int j = i;
        while (s[j] != ' ' && j < n) {
          ++j;
        }
        std::reverse(s.begin() + i, s.begin() + j);
        
        i = j;
      }
      
      return s;
    }
};
/**
 * 
 * @param s string字符串 
 * @param n int整型 
 * @return string字符串
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
char* trans(char* s, int n ) {
  char *str = (char *)malloc(strlen(s) + 1);
  memcpy(str, s, strlen(s) + 1);
  
  for (int i = 0; i < n; ++i) {
    if (str[i] >= 'A' && str[i] <= 'Z') {
      str[i] = tolower(str[i]);
    } else if (str[i] >= 'a' && str[i] <= 'z') {
      str[i] = toupper(str[i]);
    }
  }
  
  for (int i = 0, j = n - 1; i < j; ++i, --j) {
    char tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
  
  for (int i = 0; i < n; ++i) {
    int j = i;
    while (str[j] != ' ' && j < n) {
      ++j;
    }
    
    int front = i, back = j - 1;
    
    while (front < back) {
      char tmp = str[front];
      str[front] = str[back];
      str[back] = tmp;
      ++front;
      --back;
    }
    
    i = j;
  }
  
  return str;
}
全部评论
那个请问为啥我include了头文件后,tolower toupper islower这些函数还是无法被识别编译报错呢?
点赞 回复 分享
发布于 03-09 22:32 重庆

相关推荐

想出去带家人放松顺便自己也休息下,但怕有时间冲突
白火同学:如果国庆真有面试,那国庆都不放假的公司,未免也太压榨了,还是避坑吧。
我的秋招日记
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务