牛客NC353 回文子串的数量【中等 字符串,枚举,回文 C++/Java/Go/PHP 高频】

题目

题目链接:

https://www.nowcoder.com/practice/3e8b48c812864b0eabba0b8b25867738

思路


参考答案C++

cpp 复制代码
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @return int整型
     */
    int Substrings(string str) {
        //枚举每一个中心向两边扩展
        int n = str.size();
        int ans = 0;
        for (int i = 0; i < 2 * n - 1; i++) {
            int left = i / 2;
            int right = i / 2 + i % 2;

            while (left >= 0 && right < n && str[left] == str[right]) {
                left--;
                right++;
                ans++;
            }
        }
        return ans;
    }
};

参考答案Java

java 复制代码
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @return int整型
     */
    public int Substrings (String str) {
        //枚举每一个中心扩展
        int n = str.length();
        int ans = 0;
        for (int i = 0; i < 2 * n - 1; i++) {
            int left = i / 2;
            int right = i / 2 + i % 2;

            while (left >= 0 && right < n && str.charAt(left) == str.charAt(right)) {
                ans++;
                left--;
                right++;
            }
        }
        return ans;
    }
}

参考答案Go

go 复制代码
package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param str string字符串
 * @return int整型
 */
func Substrings(str string) int {
	//枚举每一个中心向两边扩展
	n := len(str)
	ans := 0
	for i := 0; i < 2*n-1; i++ {
		left := i / 2
		right := i/2 + i%2

		for left >= 0 && right < n && str[left] == str[right] {
			left--
			right++
			ans++
		}
	}
	return ans
}

参考答案PHP

php 复制代码
<?php


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param str string字符串 
 * @return int整型
 */
function Substrings( $str )
{
       //枚举每一个中心向两边扩展
    $n = strlen($str);
    $ans = 0;

    for($i=0;$i<2*$n-1;$i++){
        $left = intval($i/2);
        $right = intval($i/2)+$i%2;

        while ($left >=0 && $right <$n && $str[$left] ==$str[$right]){
            $left--;
            $right++;
            $ans++;
        }
    }
    return $ans;
}
相关推荐
wen__xvn1 小时前
每日一题洛谷P1914 小书童——凯撒密码c++
数据结构·c++·算法
BUG 劝退师2 小时前
八大经典排序算法
数据结构·算法·排序算法
m0_748240912 小时前
SpringMVC 请求参数接收
前端·javascript·算法
小林熬夜学编程3 小时前
【MySQL】第八弹---全面解析数据库表的增删改查操作:从创建到检索、排序与分页
linux·开发语言·数据库·mysql·算法
小小小白的编程日记3 小时前
List的基本功能(1)
数据结构·c++·算法·stl·list
_Itachi__3 小时前
LeetCode 热题 100 283. 移动零
数据结构·算法·leetcode
柃歌3 小时前
【UCB CS 61B SP24】Lecture 5 - Lists 3: DLLists and Arrays学习笔记
java·数据结构·笔记·学习·算法
鱼不如渔3 小时前
leetcode刷题第十三天——二叉树Ⅲ
linux·算法·leetcode
qwy7152292581633 小时前
10-R数组
python·算法·r语言
月上柳梢头&3 小时前
[C++ ]使用std::string作为函数参数时的注意事项
开发语言·c++·算法