算法-判斷字符串的循環移動

判斷字符串的循環移動

難度:簡單

描述:

能夠檢驗某個單詞是否爲另外一個單詞的子字符串。給定 s1 和 s2,請設計一種方法來檢驗 s2 是否爲 s1 的循環移動後的字符串。javascript

樣例:

s1 = waterbottle;
s2 = erbottlewat;
返回true;前端

s1 = apple;
s2 = ppale;
返回false;java

思路分析:

將其中一個字符串轉成數組來操做,而後再轉成字符,回頭來比較字符串。數組

代碼模板:

/**
 * @param s1: the first string
 * @param s2: the socond string
 * @return: true if s2 is a rotation of s1 or false
 */

const isRotation = function(s1, s2{};

想想再看答案

想想再看答案

想想再看答案

代碼:

// 將最後的值拿出來 再放到第一位上去
const isRotation = (s, t) => {
  if (s.length === t.length && s && t) {
    for (let i = 0; i < s.length; i++) {
      t = [...t]; // 轉數組
      let pop = t.pop(); // 拿最後一個元素
      t.unshift(pop); // 添加到第一個元素
      t = t.join(''); // 轉字符
      if (t === s) return true// 比較
    }
  }
  return false// 字符串長度相等 而且有值
};
console.log(
  '輸出:',
  isRotation('waterbottle''erbottlewat'),
  isRotation('apple''ppale')
);

鼓勵我一下:

以爲還不錯的話,給個人項目點個star吧微信

判斷字符串的循環移動

難度:簡單

描述:

能夠檢驗某個單詞是否爲另外一個單詞的子字符串。給定 s1 和 s2,請設計一種方法來檢驗 s2 是否爲 s1 的循環移動後的字符串。app

樣例:

s1 = waterbottle;
s2 = erbottlewat;
返回true;ui

s1 = apple;
s2 = ppale;
返回false;spa

思路分析:

將其中一個字符串轉成數組來操做,而後再轉成字符,回頭來比較字符串。.net

代碼模板:

/**
 * @param s1: the first string
 * @param s2: the socond string
 * @return: true if s2 is a rotation of s1 or false
 */

const isRotation = function(s1, s2{};

想想再看答案

想想再看答案

想想再看答案

代碼:

// 將最後的值拿出來 再放到第一位上去
const isRotation = (s, t) => {
  if (s.length === t.length && s && t) {
    for (let i = 0; i < s.length; i++) {
      t = [...t]; // 轉數組
      let pop = t.pop(); // 拿最後一個元素
      t.unshift(pop); // 添加到第一個元素
      t = t.join(''); // 轉字符
      if (t === s) return true// 比較
    }
  }
  return false// 字符串長度相等 而且有值
};
console.log(
  '輸出:',
  isRotation('waterbottle''erbottlewat'),
  isRotation('apple''ppale')
);

鼓勵我一下:

以爲還不錯的話,給個人項目點個star吧設計


本文分享自微信公衆號 - OBKoro1前端進階積累(gh_8af2fb8e54a9)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索