测试小站: 处理网 回收帮 培训网 富贵论坛 老富贵论坛

算法:415. 字符串相加

  给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。

  Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

  你不能使用任何內建的用于处理大整数的库(比如 BigInteger)

  潜台词:不能使用第三方的系统库

  也不能直接将输入的字符串转换为整数形式。

  字符串变成整数,出现越界,让问题变得更加复杂。

  思考的方向不对。让你无法专注题目本身。不是整体相加 ,变成整数相加。遍历 处理每个字符。

  潜台词:真个字符串不能变成整数,单个字符可以 ,问题转为将字符'0'-'9'转换为数字:

  非负整数

  潜台词:考虑进位

  zhihu/question/267093698

  二进制里用补码表示表示负数的好处就是不用管加数正负直接加然后直接舍去最高位的进位(溢出部分)就可以得到正确的结果

  返回字符串的长度不固定怎办? 整数相加从个位开始,读取从百位开始。顺序不一致

  潜台词:string 翻转+扩展特性

  2个链表合并,我判断长度是否一致,剩余最后一个字符串怎么处理。逻辑重复出现

  需要统一处理:c=a+b+bit

  999 +1=1000

  0999

  0001

  ---------

  1000

  潜台词: 正常访问 和越界访问 在同一个逻辑里。

  提示:

  1 <=num1.length, num2.length <=104

  潜台词:长度不相等

  num1 和num2 都不包含任何前导零

  潜台词:自己如何处理前导零

  class Solution {

  public:

  string addStrings(string num1, string num2) {

  string data; //解决长度不确定问题

  //倒序遍历,越界补0

  for( int l1=num1.size()-1, l2=num2.size()-1, bit=0;l1>=0 || l2>=0 || bit > 0;l1--,l2--)

  {

  int a=l1>=0?num1[l1]-'0':0;

  int b=l2>=0?num2[l2]-'0':0;

  int c=a+b+bit;

  bit=c/10;

  data.push_back(c%10+'0');

  }

  reverse(data.begin(),data.end());

  return data;

  }

  };

  43. Multiply Strings

  leetcode/problems/multiply-strings/

  Input: num1="123", num2="456"

  Output: "56088"

  You are given a string s, return the number of segments in the string.

  A segment is defined to be a contiguous sequence of non-space characters.

  434. Number of Segments in a String

  leetcode-cn/problems/number-of-segments-in-a-string/solution/acmjin-pai-ti-jie-you-xiao-dai-ma-wu-xin-hbsi/

  212. Word Search II

  76. Minimum Window Substring

  示例 4:

  输入:s=" Bob Loves Alice " 输出:"Alice Loves Bob"

  输入:s=" hello world " 输出:"world hello"

  解释:如果两个单词间有多余的空格,将翻转后单词间的空格减少到只含一个。

  解释:输入字符串可以在前面或者后面包含多余的空格,但是翻转后的字符不能包括。

  class Solution {

  public:

  string delSpace(string input)

  {

  //s=" hello world "

  //s="hello world "

  //two pointer

  int end=0;//new end index

  int begin=0; //old string begin index

  char temp=0;

  int spaceCount=0;

  while ( begin <input.size())

  {

  temp=input[begin];

  if( ' '==temp)

  {

  if(0==end)

  { begin++;

  continue; //不统计:

  }else

  {

  spaceCount++;//统计:分割字符的空格

  }

  }else

  {

  if(spaceCount >0)

  {

  input[end++]=' '; //分割字符的空格 保留

  spaceCount=0;// 判断字符串前排是否有空格

  }//else

  //{

  input[end++]=input[begin];

  //}

  }

  begin++;

  }

  return input.substr(0,end);//[0,end)

  }

  public:

  string reverseWords(string s) {

  string input=delSpace(s);

  int begin=0;

  int end=0;

  for(end=0;end<input.size();end++)

  {

  if(input[end]==' ')

  {

  //[start,end)是个单词

  reverse(input.begin()+begin,input.begin()+end);

  begin=end+1;

  }

  }

  //"hello"

  reverse(input.begin()+begin,input.begin()+end);

  reverse(input.begin(),input.end());

  return input;

  }

  };

posted @ 2021-12-21 14:15  linjingyg  阅读(237)  评论(0)    收藏  举报