js查找不连续子字符串
时间: 2023-11-11 16:03:33 浏览: 40
可以使用动态规划的方法来查找不连续子字符串。
具体步骤如下:
1. 定义状态:设f (i)为以第i个字符结尾的最长不连续子字符串的长度。
2. 状态转移方程:当第i个字符与前面的字符不连续时,f(i) = f(i-1)+1;否则,f(i) = 1。
3. 初始化f(1) = 1。
4. 遍历字符串,求出f(i)的最大值,即为所求的最长不连续子字符串的长度。
以下是示例代码:
```javascript
function findLongestNonContinuousSubstr(str) {
let f = new Array(str.length).fill(1);
for(let i = 1; i < str.length; i++) {
if(str.charAt(i) !== str.charAt(i-1)) {
f[i] = f[i-1] + 1;
}
}
return Math.max(...f);
}
// 示例
console.log(findLongestNonContinuousSubstr('ababc')); // 输出2,最长不连续子字符串为"ab"
console.log(findLongestNonContinuousSubstr('bbbbb')); // 输出1,最长不连续子字符串为"b"
console.log(findLongestNonContinuousSubstr('pwwkew')); // 输出3,最长不连续子字符串为"wke"
```
相关问题
js查找子字符串的函数代码
以下是一些常见的 JavaScript 查找子字符串的函数代码:
1. indexOf() 方法:
```javascript
const str = "hello world";
const substr = "world";
const index = str.indexOf(substr);
console.log(index); // 6
```
2. includes() 方法:
```javascript
const str = "hello world";
const substr = "world";
const result = str.includes(substr);
console.log(result); // true
```
3. search() 方法:
```javascript
const str = "hello world";
const substr = "world";
const index = str.search(substr);
console.log(index); // 6
```
4. match() 方法:
```javascript
const str = "hello world";
const substr = "world";
const result = str.match(substr);
console.log(result); // ["world"]
```
5. RegExp 对象:
```javascript
const str = "hello world";
const substr = "world";
const regex = new RegExp(substr);
const result = str.match(regex);
console.log(result); // ["world"]
```
以上这些函数都可以用来查找子字符串,具体使用哪个函数取决于你的需求。
js查找是否包含某个字符串
可以使用字符串的 `includes` 方法来查找是否包含某个字符串。该方法返回一个布尔值,表示目标字符串是否包含指定的字符串。
例如,如果要查找字符串 `str` 是否包含子字符串 `subStr`,可以使用以下代码:
```
if (str.includes(subStr)) {
console.log('包含该字符串');
} else {
console.log('不包含该字符串');
}
```
其中,`str` 表示目标字符串,`subStr` 表示要查找的子字符串。如果 `str` 包含 `subStr`,则输出 `包含该字符串`,否则输出 `不包含该字符串`。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)