旧题记录:https://blog.csdn.net/chamao_/article/details/143336045?fromshare=blogdetail&sharetype=blogdetail&sharerId=143336045&sharerefer=PC&sharesource=chamao_&sharefrom=from_link

C++解法:

class Solution {
public:
    bool isFlipedString(string s1, string s2) {
        size_t len1 = s1.length();
        size_t len2 = s2.length();
        if (len1 != len2) return false;
        std::string s = s1 + s1;
        if (s.find(s2) != std::string::npos) {
            return true;
        } else {
            return false;
        }
    }
};

C++知识:

虽然C++可以使用C的strstr(),但是不推荐。C++中可以使用.find(),来查找字符串1中是否包含字符串2。

C++ 的推荐替代:std::string::find ⭐⭐⭐

最常见写法

std::string s = "hello world";
size_t pos = s.find("world");

if (pos != std::string::npos) {
    // 找到了
}

优点

  • ✔ 更安全

  • ✔ 返回位置(索引)

  • ✔ 直接支持 std::string

  • ✔ 可读性高


五、对比:strstr vs find

项目 strstr string::find
是否 C++ 风格
参数类型 char* std::string
返回值 指针 索引
安全性 较低
推荐程度 仅旧代码 ⭐⭐⭐⭐⭐

npos是什么?

npos 表示“没找到(not position)”
std::string(以及 string_view 等)里专门用来表示无效位置的常量。


一、npos 是什么?

std::string 里:

static const size_t npos = -1;

也就是说:

  • npos 是一个 size_t 类型

  • 值等于 size_t 能表示的最大值

在 64 位系统上通常是:

18446744073709551615 // 2^64 - 1


二、为什么需要 npos

因为 C++ 的 find 系列函数:

size_t pos = s.find("abc");

返回的是 位置(下标)

  • 找到 → 返回 0、1、2…

  • 没找到 → 不能返回 -1(因为 size_t 是无符号)

所以 C++ 定义了一个“特殊值”来表示失败:

👉 npos = not position

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐