1. 程式人生 > 其它 >演算法:415. 字串相加

演算法: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;

  }

  };