var reverseString = function(s) {
for(let i = 0;i <Math.floor(s.length /2); i++ ){
let tmp = s[i]
s[i] = s[s.length - 1 - i]
s[s.length - 1 - i] = tmp
}
};
var reverseStr = function(s, k) {
let arr = s.split('')
function reverseEach(start, end){
let i = start
let j = end - 1
while(i < j){
let tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
i ++
j --
}
}
let len = Math.floor(arr.length / (2*k) )
let res = arr.length % (2*k)
if(res >= k) reverseEach(2*k*len,2*k*len + k)
else reverseEach(2*k*len, arr.length)
while(len){
reverseEach(2*k*(len-1),2*k*(len-1) + k)
len --
}
return arr.join('')
};
s 转换为 数组,遍历数组,当发现元素为空格,则替换为 %20
var replaceSpace = function(s) {
let arr = s.split('')
for(let i = 0; i < arr.length ; i++){
if(arr[i] === ' ') arr[i] = '%20'
}
return arr.join('')
};
- 先将字符串首尾空格去掉
- 字符串转换为数组,分隔符为空格
- 遍历数组,元素为空字符串的去除
- 反转数组,再转为字符串返回
var reverseWords = function(s) {
s = s.trim()
let arr = s.split(' ')
for(let i = 0; i < arr.length; i++){
if(arr[i] === ''){
arr.splice(i,1)
i --
}
}
arr.reverse()
return arr.join(' ')
};
局部翻转 + 整体翻转 不使用额外空间
- 反转前n个字符,反转n+1到结束这部分字符
- 再整体反转
var reverseLeftWords = function(s, n) {
let arr = s.split('')
function reverseStr(start,end){
console.log('reverse:',start,end)
let i = start
let j = end - 1
while(i<j){
let tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
i ++
j --
}
console.log(arr)
}
reverseStr(0,n)
reverseStr(n,arr.length)
reverseStr(0,arr.length)
return arr.join('')
};
或者这样
把前部分截取下来,slice也可以截取字符串,再将转换为数组的前部分删除,再转换为字符串,最终与front拼接后返回
var reverseLeftWords = function(s, n) {
let arr = s.split('')
let front = s.slice(0,n)
arr.splice(0,n)
return arr.join('') + front
};
KMP 算法
var strStr = function(haystack, needle) {
if(needle === '') return 0
let next = new Array(needle.length)
next.fill(0)
function getNext(str){
let j = 0
for(let i = 1; i < str.length; i++){
while(j > 0 && str[i] !== str[j]){
j = next[j - 1]
}
if(str[i] === str[j]){
j ++
}
next[i] = j
}
}
getNext(needle)
let j = 0
for(let i = 0; i < haystack.length; i++){
while(j > 0 && haystack[i] !== needle[j]){
j = next[j - 1]
}
if(haystack[i] === needle[j]){
j ++
}
if(j === needle.length){
return i - needle.length + 1
}
}
return -1
};
len 为数组长度,next为最大相等前后缀数组,如果 len % (len - next[len - 1]) === 0 成立,则该字符串符合题意。next[len - 1]表示整个字符串的最大相等前后缀长度,对于符合题意的字符串,len - next[len - 1]就是重复的子串,也就是第一个周期,则len对其取余为0。反之则不会满足这样的关系。
var repeatedSubstringPattern = function(s) {
let next = new Array(s.length).fill(0)
function getNext(str){
let j = 0
for(let i = 1; i < s.length; i++){
while(j > 0 && str[i] !== str[j]){
j = next[j - 1]
}
if(str[i] === str[j]){
j ++
}
next[i] = j
}
}
getNext(s)
if(next[s.length - 1] === 0) return false
if(s.length % (s.length - next[s.length - 1]) === 0)
return true
return false
};
|